Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global logging [duplicate]

Tags:

python

logging

How do I make a Logger global so that I can use it in every module I make?

Something like this in moduleA:

import logging
import moduleB

log = logging.getLogger('')

result = moduleB.goFigure(5)
log.info('Answer was', result)

With this in moduleB:

def goFigure(integer):
    if not isinstance(integer, int):
        log.critical('not an integer')
    else:
        return integer + 1

Currently, I will get an error because moduleB does not know what log is. How do I get around that?

like image 881
MFB Avatar asked Jun 21 '12 04:06

MFB


2 Answers

You could make your own logging "module" which instantiates the logger, than have all of your code import that instead. Think:

logger.py:

import logging
log = logging.getLogger('')

codeA.py:

from logger import log
log.info('whatever')

codeB.py:

from logger import log
log.warn('some other thing')
like image 75
Haldean Brown Avatar answered Oct 18 '22 11:10

Haldean Brown


Creating a global logger which can be used to

  1. create a new log file or
  2. returns logger for a global log file.

Create a module called called myLogger.py : This will have the log creation code

myLogger.py:

import logging

def myLog(name, fname = 'myGlobalLog.log'):
'''Debug Log'''                                                                                                 
    logger = logging.getLogger(name);                                                                               
    logger.setLevel(logging.DEBUG)                                                                                  
    fhan = logging.FileHandler(fname)                                                                               
    fhan.setLevel(logging.DEBUG)                                                                                    
    logger.addHandler(fhan)                                                                                         
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')                           
    fhan.setFormatter(formatter)
    '''comment this to enable requests logger'''                                                                    
    #logger.disabled = True
    return logger

Now to create a new log in your module say A.py

from myLogger import myLog
log = myLog(__name__, 'newLog.log')
log.debug("In new log file")

Thus you have to pass the file name along while getting the logger.

To use the global logger in A.py:

from myLogger import myLog
log = myLog(__name__)
log.debug("In myGlobalLog file")

Need not pass the file name in this case as we gonna use the global log.

like image 23
Hari Priya Thangavel Avatar answered Oct 18 '22 11:10

Hari Priya Thangavel