logger chain in python

2024/9/20 9:42:01

I'm writing python package/module and would like the logging messages mention what module/class/function they come from. I.e. if I run this code:

import mymodule.utils.worker as workerw = worker.Worker()
w.run()

I'd like to logging messages looks like this:

2010-06-07 15:15:29 INFO mymodule.utils.worker.Worker.run <pid/threadid>: Hello from worker

How can I accomplish this?

Thanks.

Answer

I tend to use the logging module in my packages/modules like so:

import logging
log = logging.getLogger(__name__)
log.info("Whatever your info message.")

This sets the name of your logger to the name of the module for inclusion in the log message. You can control where the name is by where %(name)s is found in the format string. Similarly you can place the pid with %(process)d and the thread id with %(thread)d. See the docs for all the options.

Formatting example:

import logging
logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s %(process)d/%(threadName)s: %(message)s")
logging.getLogger('this.is.the.module').warning('Testing for SO')

Gives me:

2010-06-07 08:43:10,494 WARNING this.is.the.module 14980/MainThread: Testing for SO
https://en.xdnf.cn/q/72364.html

Related Q&A

How to make data to be shown in tabular form in discord.py?

Hi I am creating a bot that makes points table/leaderboard , below is the code which works really nice. def check(ctx):return lambda m: m.author == ctx.author and m.channel == ctx.channelasync def get_…

Getting Python version using Go

Im trying to get my Python version using Go:import ("log""os/exec""strings" )func verifyPythonVersion() {_, err := exec.LookPath("python")if err != nil {log.Fata…

Python shutil.copytree() is there away to track the status of the copying

I have a lot of raster files (600+) in directories that I need copy into a new location (including their directory structure). Is there a way to track the status of the copying using shutil.copytree()?…

Py2exe error: [Errno 2] No such file or directory

C:\Users\Shalia\Desktop\accuadmin>python setup_py2exe.py py2exe running py2exe10 missing Modules------------------ ? PIL._imagingagg imported from PIL.ImageDraw ? PyQt4 …

pandas rolling window mean in the future

I would like to use the pandas.DataFrame.rolling method on a data frame with datetime to aggregate future values. It looks it can be done only in the past, is it correct?

When should I use type checking (if ever) in Python?

Im starting to learn Python and as a primarily Java developer the biggest issue I am having is understanding when and when not to use type checking. Most people seem to be saying that Python code shoul…

Kartograph python script generates SVG with incorrect lat/long coords

I have modified this question to reflect some progress on discovering the problem. I am using the following python code to generate an SVG of the continental USA. The shapefile is irrelevant, as the …

Python multiprocessing blocks indefinately in waiter.acquire()

Can someone explain why this code blocks and cannot complete?Ive followed a couple of examples for multiprocessing and Ive writting some very similar code that does not get blocked. But, obviously, I…

What is the best way to control Twisteds reactor so that it is nonblocking?

Instead of running reactor.run(), Id like to call something else (I dunno, like reactor.runOnce() or something) occasionally while maintaining my own main loop. Is there a best-practice for this with …

Accessing the content of a variable array with ctypes

I use ctypes to access a file reading C function in python. As the read data is huge and unknown in size I use **float in C . int read_file(const char *file,int *n_,int *m_,float **data_) {...}The func…