Home > Uncategorized > Unicode support for Python’s logging library

Unicode support for Python’s logging library

February 3rd, 2009 admin Leave a comment Go to comments
class MyFormatter(logging.Formatter):
  def __init__(self, fmt=None, datefmt=None, encoding='windows-1250'):
    logging.Formatter.__init__(self, fmt, datefmt)
    self.encoding = encoding
 
  def formatException(self, ei):
    r = logging.Formatter.formatException(self, ei)
    if type(r) in [types.StringType]:
      r = r.decode('windows-1250', 'replace') # Convert to unicode
    return r
 
  def format(self, record):
    t = logging.Formatter.format(self, record)
    if type(t) in [types.UnicodeType]:
      t = t.encode(self.encoding, 'replace')
    return t
 
 
def prepareFileAndConsoleLogging(soubor, urovenSoubor=None, urovenKonzole=None):
  # http://docs.python.org/library/logging.html
  global logging, libLogger
 
  if urovenSoubor == None:
    urovenSoubor = logging.DEBUG
  if urovenKonzole == None:
    urovenKonzole = logging.INFO
 
  #logging.basicConfig(level=urovenSoubor)
 
  # Soubor
  fileH = logging.FileHandler(soubor, 'a')
  fileH.setLevel(urovenSoubor)
  formatterF = MyFormatter(
    fmt='%(asctime)s|%(levelname)-8s|%(name)s|%(message)s|%(filename)s|%(funcName)s|%(lineno)d',
    encoding='windows-1250')
  fileH.setFormatter(formatterF)
  logging.getLogger('').addHandler(fileH)
  logging.getLogger('').setLevel(urovenSoubor)
 
  # Konzole
  console = logging.StreamHandler()
  console.setLevel(urovenKonzole)
  formatter = MyFormatter(
    fmt='%(name)s: %(message)s',
    encoding='cp852')
  console.setFormatter(formatter)
  logging.getLogger('').addHandler(console)
 
  libLogger.info(u'UNICODE: Logování inicializováno (diakritika: ščřžýáíé)')
  libLogger.info('STRING: Logování inicializováno (diakritika: ščřžýáíé)')
  libLogger.debug(u'Debug')
Bookmark and Share
Tags:
  1. No comments yet.
  1. No trackbacks yet.
Security Code: