How to share a file between modules for logging in python

2024/11/19 19:19:44

I wanted to log messages from different module in python to a file. Also I need to print some messages to console for debugging purpose. I used logger module for this purpose . But logger module will log all the logs with given severity and above to file or console.

I wanted only some messages logged to file and it should not include the messages from the console.

Similarly the console messages should not contain messages logged to file.

My approach would be to have a singleton class which shares file write operation between various modules.

Is there any easier approach than this in python ?

EDIT: I am new to Python. Sample program I tried

logger = logging.getLogger('simple_example')
logger.setLevel(logging.INFO)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.CRITICAL)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

Console prints :

2015-02-03 15:36:00,651 - simple_example - ERROR - error message
2015-02-03 15:36:00,651 - simple_example - CRITICAL - critical message
#I don't want critical messages in console.
Answer

Here is a script that creates two loggers, use the one you wish to log to a file or stdout. The question is : on which criteria do you choose to log to stdout or file, knowing that (from your question) you don't want the criteria to be the log level (debug, error, critical...)

#!/usr/bin/pythonimport logginglogger_stdout = logging.getLogger('logger_stdout')
logger_stdout.setLevel(logging.DEBUG)
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger_stdout.addHandler(sh)
logger_stdout.debug('stdout debug message')logger_file = logging.getLogger('logger_file')
logger_file.setLevel(logging.DEBUG)
fh = logging.FileHandler("foo.log")
fh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger_file.addHandler(fh)
logger_file.debug('file debug message')

And when I run this script:

D:\jrx\jrxpython                                                          
λ python essai.py                                                         
2015-02-03 11:12:07,210 - logger_stdout - DEBUG - stdout debug message    D:\jrx\jrxpython                                                          
λ cat foo.log                                                             
2015-02-03 11:12:07,224 - logger_file - DEBUG - file debug message        D:\jrx\jrxpython                                                          
λ   
https://en.xdnf.cn/q/118504.html

Related Q&A

Dont understand how this example one-hot code indexes a numpy array with [i,j] when j is a tuple?

I dont get how the line: results[i, sequence] = 1 works in the following.I am following along in the debugger with some sample code in a Manning book: "Deep Learning with Python" (Example 3.5…

convert nested list to normal list using list comprehension in python [duplicate]

This question already has answers here:How do I make a flat list out of a list of lists?(32 answers)Flatten an irregular (arbitrarily nested) list of lists(54 answers)Closed 6 years ago.How can I do t…

Transformation of pandas DataFrame adds a blank row

My original question was posted here. I have a dataframe as follows:ID START END SEQ 1 11 12 1 1 14 15 3 1 13 14 2 2 10 14 1 3 11 15 1 3 16 17 …

How to find a element after a search click checkbox in selenium Python

After I search for a user in the search field, I get the user I searched Now I need to select this user that shown in the list I tried with xpath and did not find the element ! could you help ? So aft…

Running parameterized queries

Quite new to this google bigquery sql thing so please bear with me. Im trying to build a google standardSQL parameterized query. The following sample was used and ran successfully on Google BigQuery We…

how to do this disparity map in OpenCV

paper "Fast Obstacle Detection Using U-Disparity Maps with Stereo Vision"reference paper: "Fast Obstacle Detection Using U-Disparity Maps with Stereo Vision"I want to ask can opencv…

How do I give out a role when I click on a reaction? It doesnt work for me?

Im trying to make sure that when you enter a command, a message is sent and a reaction is set, and those who click on the reaction get a role, but when you enter a command, nothing happens. Here is the…

Python Pandas DataFrame Rounding of big fraction values [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Splitting Data in Python?

it does not work. I want to split data as in code in lines attribute. class movie_analyzer:def __init__(self,s):for c in punctuation:import removiefile = open(s, encoding = "latin-1")movielis…

Use local function variable inside loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 7 years ago.Improve…