Monday, February 1, 2016

How to configure logger in python?

How to configure logger in python?

In this page we have given how to configure a basic logging using python logging module.

==
import threading
import time
import logging
def configLogger():
   logging.basicConfig(level=logging.DEBUG,
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
                    )

def task(name,age=20):
      logging.info(threading.currentThread().getName() + 'Start...')
      time.sleep(2)
      print name,age
      logging.debug(threading.currentThread().getName() + 'End...')
threads=[]
for i in range(5):
    t = threading.Thread(target=task, args=(i,),kwargs={'age':21})
    t.setDaemon(True)
    threads.append(t)
    #t.start()
configLogger()
logging.debug("using logger")
[x.start() for x in threads]
===

Output:
[DEBUG] (MainThread) using logger
[INFO] (Thread-1 ) Thread-1Start...
[INFO] (Thread-2 ) Thread-2Start...
[INFO] (Thread-3 ) Thread-3Start...
[INFO] (Thread-4 ) Thread-4Start...

How to redirect output of logger into a file?

We can redirect the logger output into a file instead of stdout/stderr file. We might need this file for future reference. In below code snippet I have shown how to configure the logger to redirect its output into a file. It is very useful when we try to develop any application.

==========
def Logger(logDir, fileName=None):
   logFormat = logging.Formatter('%(asctime)s [%(levelname)s %(filename)s::'
                                 '%(funcName)s::%(lineno)s] %(message)s')
   handler = logging.StreamHandler(sys.stdout)
   handler.setLevel(logging.DEBUG)
   handler.setFormatter(logFormat)
   log = logging.getLogger("basic")
   log.level = logging.DEBUG
   log.addHandler(handler)

   if not fileName:
      t = time.time()
      timeStr = time.strftime("%d%b%Y-%H%M", time.gmtime(t))
      timeStr = "%.3f-%s" % (t, timeStr)
      fileName='Test-%s.log' % timeStr
   fhandler = logging.FileHandler("%s/%s" % (logDir, fileName))
   fhandler.setLevel(logging.DEBUG)
   fhandler.setFormatter(logFormat)
   log.addHandler(fhandler)
   return log
==========

No comments:

Post a Comment