single logger in python project?
I'd li开发者_StackOverflow社区ke to create a logger for a python project. I want to make sure that i'm using the same logger for every module in the project. What is the best way to do this? It seems I need a global logging object? Or perhaps a logging module that is imported by every other module? I want to make sure that I'm always writing to the same log file.
I'm using python's logger and handler already. The problem is that I have to define which file the logger will write to in every module. I'd like to define the log file path once and have it be used for every module.
As you say, look at Python's logging
module
It provides objects like Logger and Handler, I think it can work for you.
The singleton pattern is ideal for situations like this. In Python, you'd implement it something like this:
class MySingleton(object):
__instance = None
def __init__(self):
if self.__class__.__instance:
raise Exception, """
Tried to allocate a second instance of a singleton.
Use getInstance() instead.
"""
self.__class__.__instance = self
@classmethod
def getInstance(cls):
if not cls.__instance:
cls()
return cls.__instance
Then you can import the module as you normally would and use MySingleton.getInstance() to get an instance of the class. Within a given application, you're guaranteed that you'll always get the same instance.
EDIT: Others have pointed out the logging module, and I'd agree with them that using that is probably a better option than writing your own logger. However, if you do need to write your own logger for whatever reason, the above pattern is probably what you'll want to use.
Define the logger object in the __builtin__ module. That way, you can access it like any other python global function, without importing some logging module in every file.
in logmodule.py:
import __builtin__
__builtin__.log = logging.getLogger('global')
# ... configure your logger
In your 'main' file:
import logmodule
In some other file:
log.debug('blah')
use negar module ...
github negar module
install negar ...
python3 -m pip install negar
code
from negar import log
# method one
def x():
text = 'hello world!'
return text
log('\'x\' function return value is '+'\''+str(x())+'\'')
# method two
def y():
text = 'hello world!'
return text
log(text = '\'y\' function return value is '+'\''+str(x())+'\'' , save = 'function-log.txt' , size = 1)
result
精彩评论