Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing logging's 'basicConfig' which is already set

Tags:

python

logging

I am using the logging module in python as:

import logging, sys logger= logging.getLogger(__file__) logging.basicConfig(stream = sys.stderr, level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s') logger.debug("Hello World") 

Now, after I have set the basic configuration on line 3, I want to have a command line argument that can change the output stream from sys.stderr to a file.

I have read the doc and it says that if both filename and stream are present at the same time, the stream is ignored.

Now, I wanna know how do change the stream to a file after I have already done the basicConfig thing in line 3?

like image 579
Abhijeet Rastogi Avatar asked Aug 28 '12 11:08

Abhijeet Rastogi


People also ask

How do I change logging in basicConfig?

If you look in the Python sources for logging/__init__.py , you'll see that basicConfig() sets the handlers on the root logger object by calling addHandler() . If you want to start from scratch, you could remove all existing handlers and then call basicConfig() again.

Where does logger info write to Python?

We can also use the logging. FileHandler() function to write logs to a file in Python. This function takes the file path where we want to write our logs. We can then use the addHandler() function to add this handler to our logger object.

Which of the following functions is are performed by logging in Python?

The logging module is used it whenever its functions are called such as logging. debug(), logging. error(), etc. We can also define own logger by creating an object of the Logger class.


1 Answers

If you look in the Python sources for logging/__init__.py, you'll see that basicConfig() sets the handlers on the root logger object by calling addHandler(). If you want to start from scratch, you could remove all existing handlers and then call basicConfig() again.

# Example to remove all root logger handlers and reconfigure. (UNTESTED) import logging  # Remove all handlers associated with the root logger object. for handler in logging.root.handlers[:]:     logging.root.removeHandler(handler)  # Reconfigure logging again, this time with a file. logging.basicConfig(filename = 'myfile.log', level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s') 
like image 161
Austin Phillips Avatar answered Sep 21 '22 05:09

Austin Phillips