The logging attribute attribute generates local time.

I use logging for my project, and the format

  'format': '% (asctime) s% (message) s'

however, the time did not match my local time. eg

2013-01-08 11: 04: 07,383 message (this is UTC-6 time)

I want to know

  • how to keep a journal using my local time
  • how to change the time format until 2013-01-08 11:04:07

I fixed it, the problem is that I need to set the time zone in the .py setting !!!

+4
source share
1 answer

From documents :

class logging.Formatter (fmt = None, datefmt = None)

Returns a new instance of the Formatter class. The instance is initialized with a format string for the message as a whole, as well as a format string for the date / time in the message. If fmt is not specified, "% (message) s" is used. If datefmt is not specified, the ISO8601 date format is used.

also:

If the format string contains '(asctime)' , formatTime() is called to format the event time.

So, you can specify datefmt or create a custom subclass of Formatter with your own override of formatTime .

And, if you want to select local time and GMT (or something else):

The default is time.localtime (); to change this for a specific formatting instance, set the converter attribute to a function with the same signature as time.localtime () or time.gmtime (). To change it for all formatters, for example, if you want all logging time to be displayed in GMT, set the converter attribute in the Formatter class.

The format and datefmt can also be passed to basicConfig if you are not using an explicit Formatter . You cannot install converter in this way, but you do not need this, since local time is used by default.

So:

 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') log = logging.getLogger(__name__) log.error('Out of cheese!') 

I started it at 16:11:30 local time, and the output is:

 2013-01-08 16:11:30 Out of cheese! 

In fact, it seems that all you are trying to do is knock out milliseconds from the standard time format, which you can do even easier by simply truncating the line:

 logging.basicConfig(format='%(asctime)-.19s %(message)s') 

However, I believe it makes sense to explicitly specify the date format.

+7
source

All Articles