简体   繁体   中英

How can I read log file?

I am learning logging in python. However, I can't find the log file anywhere. Below an example code

import logging

logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(filename='my_app.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This will get logged')

file = open('my_app.log', 'r')

Unfortunately, the result is.

FileNotFoundError: [Errno 2] No such file or directory: 'my_app.log'

I am quite puzzled. What is wrong?

Thanks to Felix, I found a solution. Combining the two logging.basicConfig lines helped. The working code looks like this:

import logging

logging.basicConfig(filename='my_app.log',
                    filemode='w',
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    level=logging.DEBUG)
logging.debug('This will get logged')

Apparently the later logging.basicConfig command will be ignored

You can modify your code as follows:

import logging

logging.basicConfig(filename="my_app.log",
                                    filemode='a',
                                    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                                    datefmt='%H:%M:%S',
                                    level=logging.DEBUG)
logging.debug('This will get logged')

file = open('my_app.log', 'r')

The issue seems like you were setting logging.basicConfig(level=logging.DEBUG) before logging.basicConfig(filename='my_app.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s') Instead you could combine them as:

logging.basicConfig(filename="my_app.log",
                                    filemode='a',
                                    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                                    datefmt='%H:%M:%S',
                                    level=logging.DEBUG)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM