pythonloggingstructured-logging

Get asctime from the logging python lib


I am using the logging python library in order to log some structured JSON. My idea was to do it manually following the example in the documentation, by giving a config with only the message :

logging.basicConfig(level=logging.INFO, format='%(message)s')

And then use json.dumps to log a structured JSON :

logging.info(
     json.dumps({ 
          'my_logger_name': self.my_name,
          'log_level': self.log_level,
          'message': message,
          'some_data': some_data,
    })
)

It works fine, but I would like to add the timestamp to my JSON.dumps. We previously got it by adding %(asctime)s to the format config. Is there a way to get it programmatically from the logging library?

I was expecting something like : logging.getLogger().getAsctime()


Solution

  • You can get your current time by using the asctime method from time library, but its important to get your current time first.

    import time
    
    your_time = time.localtime()
    your_asc= time.asctime(t)
    

    Later you can put this in your json as you want:

      logging.info(
           json.dumps({ 
             'my_logger_name': self.my_name,
             'log_level': self.log_level,
             'message': message,
             'some_data': some_data,
             'time': your_asc
           })
    
       )