Home | History | Annotate | Download | only in pseudomodem
      1 #!/usr/bin/env python
      2 # Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
      3 # Use of this source code is governed by a BSD-style license that can be
      4 # found in the LICENSE file.
      5 
      6 # This module brings together the magic to setup logging correctly for
      7 # pseudomodem.
      8 
      9 import logging
     10 import logging.handlers
     11 import os
     12 import sys
     13 
     14 SYSLOG_DEVICE = '/dev/log'
     15 
     16 class ModemManagerFormatter(logging.Formatter):
     17     """
     18     Format log strings such that rsyslogd handles them correctly.
     19 
     20     By adding a prefix 'ModemManager[xxx]' where |xxx| contains the pid, we can
     21     ensure that rsyslogd treats the messages the same way it treats messages
     22     from ModemManager.
     23 
     24     """
     25     def __init__(self, *args, **kwargs):
     26         super(ModemManagerFormatter, self).__init__(*args, **kwargs)
     27         self._pid = os.getpid()
     28 
     29 
     30     def format(self, record):
     31         """
     32         The main function that converts log records to strings.
     33 
     34         @param record: The log record.
     35         @returns: The formatted log string.
     36 
     37         """
     38         result = super(ModemManagerFormatter, self).format(record)
     39         return 'pseudomodem[%d]: %s' % (self._pid, result)
     40 
     41 
     42 def SetupLogging():
     43     """
     44     The main function that sets up logging as expected. It does the following:
     45 
     46     (1) Clear out existing logging setup that leaks in during autotest import.
     47     (2) Setup logging handler to log to stdout
     48     (3) Setup logging handler to log to syslog.
     49 
     50     """
     51     root = logging.getLogger()
     52     for handler in root.handlers:
     53         root.removeHandler(handler)
     54 
     55     stdout_handler = logging.StreamHandler(sys.stdout)
     56     stdout_formatter = logging.Formatter(
     57         fmt='%(asctime)s %(levelname)-5.5s| %(message)s',
     58         datefmt='%H:%M:%S')
     59     stdout_handler.setFormatter(stdout_formatter)
     60     root.addHandler(stdout_handler)
     61 
     62     syslog_handler = logging.handlers.SysLogHandler(
     63             SYSLOG_DEVICE,
     64             facility=logging.handlers.SysLogHandler.LOG_DAEMON)
     65     syslog_formatter = ModemManagerFormatter(
     66         fmt='%(levelname)-5.5s|%(module)10.10s:%(lineno)4.4d| %(message)s')
     67     syslog_handler.setFormatter(syslog_formatter)
     68     root.addHandler(syslog_handler)
     69