I want to print the current timestamp, when an event succeeded or not in my python script. By only adding…
JavaScript
x
2
1
datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
2
…. at the beginning of each line, te same date appears in every line
JavaScript
1
7
1
[INFO] 04.Feb 2015 20:49:41: cl1
2
[ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE!
3
[INFO] 04.Feb 2015 20:49:41: cl2
4
[ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE!
5
[INFO] 04.Feb 2015 20:49:41: cl3
6
[ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE!
7
(I added time.sleep(5)
in between)
My next idea was to create a function, calling the current time, but i’m failing at embedding this function to the print
command.
File rs.py
JavaScript
1
6
1
OK = "[" + bc.OKGREEN + " OK " + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
2
INFO = "[" + bc.OKBLUE + "INFO" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
3
WARN = "[" + bc.WARN + "WARN" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
4
ERR = "[" + bc.ERR + "FAIL" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
5
DEB = "[" + bc.HEADER + "DEBUG" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
6
File myapp.py
JavaScript
1
6
1
import rs # importing rs.py
2
3
print rs.OK + hostname + "is up!"
4
time.sleep(3)
5
print rs.ERR+ hostname + "is down!"
6
Is printing:
JavaScript
1
3
1
>>> [INFO] 04.Feb 2015 20:49:41: xxx is up!
2
>>> [ERR ] 04.Feb 2015 20:49:41: xxx is down!
3
Advertisement
Answer
Before the first time you log anything do this:
JavaScript
1
5
1
logging.basicConfig(
2
format='%(asctime)s %(levelname)-8s %(message)s',
3
level=logging.INFO,
4
datefmt='%Y-%m-%d %H:%M:%S')
5
Example on the REPL:
JavaScript
1
11
11
1
>>> import logging
2
>>> logging.basicConfig(
3
format='%(asctime)s %(levelname)-8s %(message)s',
4
level=logging.INFO,
5
datefmt='%Y-%m-%d %H:%M:%S')
6
>>>
7
>>> logging.info('an info messge')
8
2017-05-25 00:58:28 INFO an info messge
9
>>> logging.debug('a debug messag is not shown')
10
>>>
11