ตัวอย่าง log ใน python


filename: code_has_error.py
logfile : logtest.log

import logging
import sys
import os
from datetime import datetime
log_path = os.getcwd()+'/' #set to running directory
loglevel = 'DEBUG' #default log level
#change path to some path
#log_path = '/path/to/log/'
def ensure_file(filename):
    f = open(filename, 'a')
    f.close()
    return filename
def today_logname() :
    return datetime.today().strftime('%Y-%m-%d.log')
def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)
def configLog():
    global loglevel
    if len(sys.argv) > 1:
      for argu in sys.argv:
          if argu.startswith('--log='):
              loglevel = argu[6:]
    numeric_level = getattr(logging, loglevel.upper()) #geting log level
    if not isinstance(numeric_level , int):
        raise ValueError ('Invalid log level: %s' % loglevel)
    ensure_dir(log_path)

    full_path = ensure_file(log_path+today_logname())
    logging.basicConfig(filename=full_path,
                      format='%(asctime)s:%(levelname)s:%(message)s',
                       level=numeric_level,
                     datefmt='%d/%b/%Y %I:%M:%S %p')
def main():
  configLog()
  logging.info('Log level :%s.' % loglevel)
  logging.debug('This message should go to the log file in debug mode')
  logging.warning('Watch out!')
  a = 100 / 0
  logging.info('I told you so.')

if __name__ == '__main__':
 try:
   main()
 except :
   logging.exception('')

test run than see log result in .log


18/Apr/2012 05:10:38 PM:INFO:Log level :INFO.
18/Apr/2012 05:10:38 PM:WARNING:Watch out!
18/Apr/2012 05:10:38 PM:ERROR:
Traceback (most recent call last):
  File "code_has_error.py", line 24, in <module>
    main()
  File "code_has_error.py", line 19, in main
    a = 100 / 0
ZeroDivisionError: integer division or modulo by zero

update: จากเดิมไม่ ready to use ตอนนี้ ready แล้วจ้า

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s