# This model file defines some magic to implement app_wide_log.
import os,logging
try:
  import logging.handlers
except ImportError: # It happens when some windows binary builder did not pack lib/logging/* well
  app_logging = logging
else:
  def _init_log(): # Does not work on GAE
    logging.warn('Entering _init_log()... This should appear only once.')
    logger = logging.getLogger(request.application)
    if not logger.isEnabledFor(# By default, a logger is NOT enabled for debug
        logging.DEBUG # We use this as a flag to make sure the logger won't be initialized multiple times
        ): # (It could happened due to some unknown problem of cache!)
      logging.warn(# This should not be showed during almost every click
        'Initializing app logger %s(#%s)... This MUST appear only once.'%(request.application,id(logger)))
      logger.setLevel(logging.DEBUG)
      handler = logging.handlers.RotatingFileHandler(
        os.path.join( # so that it can be served as http://.../yourapp/static/applog.txt
          request.folder,'static','applog.txt'),'a',1024*128,1)
      handler.setLevel(logging.DEBUG)
      handler.setFormatter(logging.Formatter(
        "%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s(): %(message)s"))
      logger.addHandler(handler)
    return logger
  app_logging = cache.ram('app_wide_log',lambda:_init_log(),time_expire=None)
