Reputation: 20658
I've set my Python program to log output, but although it logs correctly to the console, it does not log the time, log level information etc to the file.
Program:
import time
import logging
from logging.handlers import RotatingFileHandler
logFileName = 'logs.log'
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
log = logging.getLogger(__name__)
handler = RotatingFileHandler(logFileName , maxBytes=2000 , backupCount=5)
log.addHandler(handler)
log.setLevel(logging.INFO)
if __name__ == '__main__':
while True:
log.info("program running")
time.sleep(1)
Output to console:
INFO 05-May-22 23:20:54 - program running
INFO 05-May-22 23:20:55 - program running
INFO 05-May-22 23:20:56 - program running
INFO 05-May-22 23:20:57 - program running
INFO 05-May-22 23:20:58 - program running
INFO 05-May-22 23:20:59 - program running
INFO 05-May-22 23:21:00 - program running
Simultaneous output to file logs.log:
program running
program running
program running
program running
program running
program running
program running
How to make the full output go to the log file?
Upvotes: 1
Views: 472
Reputation: 1243
You can separately set the Formatter
for the RotatingFileHandler
handler.formatter = logging.Formatter(fmt='%(levelname)s %(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
Upvotes: 1