Printing a timestamp for logging into Python

I want to print the current timestamp when the event failed or not in my python script. Adding only ...

datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S") 

.... at the beginning of each line, the same date appears on each line

 [INFO] 04.Feb 2015 20:49:41: cl1 [ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE! [INFO] 04.Feb 2015 20:49:41: cl2 [ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE! [INFO] 04.Feb 2015 20:49:41: cl3 [ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE! 

(I added time.sleep(5) between them)

My next idea was to create a function by calling the current time, but I cannot embed this function in the print command.

Rs.py file

 OK = "[" + bc.OKGREEN + " OK " + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S") INFO = "[" + bc.OKBLUE + "INFO" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S") WARN = "[" + bc.WARN + "WARN" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S") ERR = "[" + bc.ERR + "FAIL" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S") DEB = "[" + bc.HEADER + "DEBUG" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S") 

File myapp.py

 import rs # importing rs.py print rs.OK + hostname + "is up!" time.sleep(3) print rs.ERR+ hostname + "is down!" 

Print:

 >>> [INFO] 04.Feb 2015 20:49:41: xxx is up! >>> [ERR ] 04.Feb 2015 20:49:41: xxx is down! 
+5
source share
3 answers

Something like below:

 formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') 

Check out the logging module for Python. You do not need to be confused with creating your own date, just let the logging module do it for you. This formatting object can be applied to the logging handler, so you can simply log in using logger.info('This is an info message.') . No printing requirements required.

The template procedure is used here:

 import logging def setup_custom_logger(name): formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') handler = logging.FileHandler('log.txt', mode='w') handler.setFormatter(formatter) screen_handler = logging.StreamHandler(stream=sys.stdout) screen_handler.setFormatter(formatter) logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.addHandler(handler) logger.addHandler(screen_handler) return logger >>> logger = setup_custom_logger('myapp') >>> logger.info('This is a message!') 2015-02-04 15:07:12 INFO This is a message! >>> logger.error('Here is another') 2015-02-04 15:07:30 ERROR Here is another 
+12
source

Before you register for the first time, do the following:

 logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') 

Example in REPL:

 >>> import logging >>> logging.basicConfig( ... format='%(asctime)s %(levelname)-8s %(message)s', ... level=logging.INFO, ... datefmt='%Y-%m-%d %H:%M:%S') >>> >>> logging.info('an info messge') 2017-05-25 00:58:28 INFO an info messge >>> logging.debug('a debug messag is not shown') >>> 
+9
source

The datetime is calculated when the string is formed. So in your case, only once during initialization. Instead, you should do something like this:

 def ok(hostname=None, status=None): output = ( "[" + bc.OKGREEN + " OK " + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S") ) if hostname is not None: output += ' ' + hostname if status is not None: output += ' ' + status print output 

To write to the log, simply use ok() , which will re-evaluate the date and time each time.

Please note that @paidhima's suggestion is also good.

0
source

Source: https://habr.com/ru/post/1212645/


All Articles