MattiH
MattiH

Reputation: 654

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

Upvotes: 0

Views: 359

Answers (1)

Felix K Jose
Felix K Jose

Reputation: 892

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)

Upvotes: 2

Related Questions