code base 5000
code base 5000

Reputation: 4102

Python Logging, Not Writing Timestamp to Output File

I am creating a log using the following statement:

module = sys.modules['__main__'].__file__
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG,
                format='%(asctime)s %(name)s (%(levelname)s): %(message)s')
log = logging.getLogger(module)

I then have an option on my script to write the output to a file using an argument -o. I think it's an issue with this statement that occurs when a person specifies that they want the log written to disk:

 if arguments.o:
    fh = RotatingFileHandler(arguments.o, mode='a', maxBytes=2*1024*1024,
                        backupCount=2, encoding=None, delay=0)
    fh.setLevel(logging.DEBUG)
    log.addHandler(fh)

Without adding an additional datetime statement to the text string, is there a way to do this using the format parameter?

Here is what is produced on print:

2015-11-06 07:27:13,592 C:\GIS\move_content\src\updatecontent.py (INFO): Reading Configuration file

Here is what is the configuration outputs:

Reading Configuration file

Thank you

Answer I found:

Based on my one response I was able to add this to my code, and the output now looks correct:

# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

Upvotes: 4

Views: 5209

Answers (1)

Penguinolog
Penguinolog

Reputation: 244

File handler uses different format string, you should set it manually to file handler too.

Example:

fh.setFormatter(formatter)

Cookbook for Python 3 (Python 2 is the same for this question)

Upvotes: 3

Related Questions