6

I set the time zone in the settings.py file of my django project:

TIME_ZONE = 'US/Eastern'

and now my logs contain US/Eastern times.

I would like to keep an UTC time in my logs. Is that possible?

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
Michael
  • 8,357
  • 20
  • 58
  • 86

1 Answers1

15

Django uses Python's logging facilities, so there shouldn't be anything Django-specific here.

According to the logging documentation, setting logging.Formatter.converter = time.gmtime should make all logs output in UTC.

Alternatively, you can make your own Formatter class to use UTC:

class UtcFormatter(logging.Formatter): 
    converter = time.gmtime

And then configure it using the () key (documented here) in the dictconfig:

LOGGING = {
    'formatters': {
        'utc': { 
            '()': 'my.package.UtcFormatter',
            'format': '...',
            'datefmt': '...',
        }
    }
}
Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102
  • Seems that this is partially working. I applied this formatter to a handler which deals with stdout logging, and what happens is that, log call that I do throughout the code, are on UTC, but the logs of HTTP requests that are registered by Django, are still on my timezone. Have any clue? Thanks for this answer anyway. – ivanleoncz Jun 10 '20 at 19:06
  • I tried both, but the thing here is that these options seems to have no interaction with Django Request logger, which is the one who registers the request. For the other logger that I have, your approaches work perfectly, with time in UTC, but the logs generated for each request (Django), timestamps still are on my timezone. I'm looking for a way to customize it. https://docs.djangoproject.com/en/2.2/_modules/django/utils/log/ – ivanleoncz Jun 10 '20 at 20:37
  • @ivanleoncz: Sorry, I'm not sure offhand. I haven't heard of this before so I suspect it has something to do with your configuration. Try posting a new question where you can give more details and a minimal example. – Kevin Christopher Henry Jun 11 '20 at 09:08