Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging between classes in python

Tags:

python

logging

I have three classes in python and they run in different threads. I would like to have output to the same file from all classes. Right now I created output method in main class and passing it through constructors to other classes. Is there way to handle it better? How I can pass the logger between classes except using contructors?

Perhaps python supports something like static method in Java, so I can write like Logger.info(message) in all three classes?

Another way probably could be redirecting global sys.stdout to the file, i.e specifying

logger = open('debug.txt', 'w')
sys.stdout = logger

Then using calls sys.stdout in all classes.

What do you think?

like image 676
yart Avatar asked Jan 18 '11 10:01

yart


People also ask

How can logger be used in multiple classes?

If you do not care about that, you can just create a single static logger instance in a class and use that all over the place. To create single logger, you can simply create a static utility logging class to be single point logger, so if we need to change the logger package, you will only update this class.

What is Python logging?

Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running. If you don't have any logging record and your program crashes, there are very few chances that you detect the cause of the problem.


1 Answers

import logging
log = logging.getLogger("mylog")
log.setLevel(logging.DEBUG)

formatter = logging.Formatter(
    "%(asctime)s %(threadName)-11s %(levelname)-10s %(message)s")
# Alternative formatting available on python 3.2+:
# formatter = logging.Formatter(
#     "{asctime} {threadName:>11} {levelname} {message}", style='{')

# Log to file
filehandler = logging.FileHandler("debug.txt", "w")
filehandler.setLevel(logging.DEBUG)
filehandler.setFormatter(formatter)
log.addHandler(filehandler)

# Log to stdout too
streamhandler = logging.StreamHandler()
streamhandler.setLevel(logging.INFO)
streamhandler.setFormatter(formatter)
log.addHandler(streamhandler)

# Test it
log.debug("Some message")
log.error("An error!")
try:
    something()
except:
    log.exception("An exception occured!")

And get in debug.txt:

2011-01-18 12:07:24,943  MainThread  DEBUG      Some message
2011-01-18 12:07:24,943  MainThread  ERROR      An error!
2011-01-18 12:07:24,943  MainThread  ERROR      An exception occured!
Traceback (most recent call last):
  File "./logtest.py", line 17, in 
    something()
NameError: name 'something' is not defined

Note that the order in which the messages appear in the log file may not correspond exactly to the order in which they happened when you're logging from several threads.

like image 191
Lauritz V. Thaulow Avatar answered Nov 01 '22 20:11

Lauritz V. Thaulow