# Copyright 2011,2012 James McCauley
#
# This file is part of POX.
#
# POX is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# POX is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with POX.  If not, see <http://www.gnu.org/licenses/>.

"""
This is a messenger service for working with the log.

It does two things:
  a) Listen on the "log" channel.  You can send messages to this
     channel with keys lowerLevels/RaiseLevels/setLevels to adjust
     global log levels.  See _process_commands() for more info.
  b) You can join any channel named log_<something> (your session
     ID is a good choice for the something), and a LogBot will
     join it.  This will result in receiving log messages.  In
     your join message (or afterwards), you can configure levels,
     the message formats, etc.  See LogService for more details.
"""

from pox.core import core
from pox.messenger import *
from pox.lib.revent.revent import autoBindEvents
import logging
import traceback

log = core.getLogger()

# These attributes are copied verbatim from the log record
_attributes = [
  'created','filename','funcName','levelname','levelno','lineno',
  'module','msecs','name','pathname','process','processName',
  'relativeCreated','thread','threadName','args',
]


class LogFilter (object):
  """
  Filters messages from the web server component

  It's a nasty situation when you're using the HTTP messenger transport
  to view the log when in debug mode, as every webserver log message
  creates a messenger message which creates a webserver message, ...

  This just turns off debug messages from the webserver.
  """
  def filter (self, record):
    if record.levelno != logging.DEBUG: return True
    if record.name == "web.webcore.server": return False
    return True


class LogHandler (logging.Handler):
  """
  A Python logging.Handler for the messenger

  Accepts dictionaries with configuration info:
  KEY            VALUE
  level          Minimum log level to output (probably one of CRITICAL,
                 ERROR, WARNING, INFO or DEBUG)
  format         fmt argument to logging.Formatter
  dateFormat     datefmt argument to logging.Formatter
  json           true if you want a bunch of attributes from the LogRecord to
                 be included.  In some cases these are stringized since  the
                 originals are objects and we don't pickle/jsonpickle them.
  subsystems     A list of logger names to listen to.  A "null"/None entry in
                 the list means the root logger (which is also the default).
  add_subsystems A list of ADDITIONAL subsystems to listen to.
  """
  #NOTE: We take advantage of the fact that the default value for the
  #      argument to getLogger() is None.  This is currently true, but
  #      isn't documented, so it might change in the future (though I
  #      don't see why it would!).  Doing this "the right way" results
  #      in much uglier code.

  def __init__ (self, channel, params):
    logging.Handler.__init__(self)
    self._channel = channel
    self.addFilter(LogFilter())
    self._json = False
    self._format = False # Not valid, should never be set
    self._dateFormat = None
    self.subsystems = []
    if "format" not in params:
      params["format"] = None # Force update
    if 'subsystems' not in params:
      self._add_subsystems([None])

    self._process_parameters(params)

  def _add_subsystems (self, subsystems):
    """
    Add log subsystems to listen to
    """
    for subsystem in subsystems:
      if subsystem in self.subsystems: continue
      try:
        logging.getLogger(subsystem).addHandler(self)
        self.subsystems.append(subsystem)
      except:
        pass

  def _drop_subsystems (self):
    """
    Stop listening to all log subsystems
    """
    for subsystem in self.subsystems:
      logging.getLogger(subsystem).removeHandler(self)
    self.subsystems = []

  def _process_parameters (self, params):
    if "level" in params:
      self.setLevel(params["level"])
    if "subsystems" in params:
      self._drop_subsystems()