Login

django log

Author:
maplye
Posted:
February 25, 2007
Language:
Python
Version:
Pre .96
Tags:
django
Score:
8 (after 14 ratings)

set LOG_FILE = "log.log" in the settings.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import logging
from django.conf import settings

def getlogger():
    logger = logging.getLogger()
    hdlr = logging.FileHandler(settings.LOG_FILE)
    formatter = logging.Formatter('[%(asctime)s]%(levelname)-8s"%(message)s"','%Y-%m-%d %a %H:%M:%S') 
    
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.NOTSET)

    return logger

def debug(msg):
    logger = getlogger()
    logger.debug(msg)
    

More like this

  1. Register django views by magik_cypress 3 years, 2 months ago
  2. django-tokenapi authentication for django-piston by yurtaev 3 years, 5 months ago
  3. django image bundle exaple template by amitu 7 years, 10 months ago
  4. django asynchronous send mail by gchandrasa 5 years ago
  5. Django authentication for django-piston by chronos 4 years, 7 months ago

Comments

jcroft (on February 25, 2007):

Looks like the language on this one should actually be "Python," not "Django Template."

#

ludvig.ericson (on February 27, 2007):

Nice. [HTML_REMOVED]"X"[HTML_REMOVED]

#

nikto (on March 2, 2007):

Maybe I'm not getting how to use this. But for me each time I call debug("some message") it adds another copy of the handler so it get dupli-tripli-quadrification of output in the log file.

#

maplye (on March 3, 2007):

i use this so that: 1.copy the code to a log.py. 2.import the log module when you use it in your code. 3.debug it.

#

jejwe (on March 5, 2007):

Another Configuration settings.py:

settings.LOG_FILE='log.txt'

#

jejwe (on March 5, 2007):

Wrong It's LOG_FILE='log.txt'

#

jejwe (on March 5, 2007):

setting.py(Configuration) :

LOG_FILE = "log.log" LOG_LEVEL = 40 #CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 NOTSET 0

#

andeol (on March 6, 2007):

nikto: the reason that you get duplicates is that each call to getLogger adds a filehandler to the logger so that for example when the fifth message is printed the there are five filehandlers each writing to the same file resulting in five duplicates of the message.

Does this code actually work for anyone?

I would suggest using a module level variable to keep track of if the logger already has been configured, to avoid doing it more than once.

#

nikto (on March 7, 2007):

andeol: yes that's what's happening and what you suggest is basically what I ended up doing.

#

nesh (on March 12, 2007):

Maybe this is better:

# stdlib
import threading
import logging
# django
from django.conf import settings

#===============================================================================
# Globals
#===============================================================================
_LOCALS = threading.local()

def get_logger():
    logger = getattr(_LOCALS, 'logger', None)
    if logger is not None:
        return logger

    logger = logging.getLogger()
    hdlr = logging.FileHandler(settings.LOG_FILE)
    formatter = logging.Formatter('[%(asctime)s]%(levelname)-8s"%(message)s"','%Y-%m-%d %a %H:%M:%S')

    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(getattr(settings, 'LOG_LEVEL', logging.NOTSET))

    return logger

#

nesh (on March 12, 2007):

I forgot, just above return logger:

setattr(_LOCALS, 'logger', logger)

#

guettli (on November 5, 2007):

Hi,

for me, the workaround with threading.local() did not work. I use the solution now:

# logconfig.py (same directory as settings.py)
def set_up():
    root_logger=logging.getLogger()
    if len(root_logger.handlers)>1:
        return
    root_logger....

And in settings.py:

import logconfig
logconfig.set_up()

#

guettli (on November 5, 2007):

The above solution works, since I insert two loggers into the root_logger. It is a hack. Remember: If you call logging.log(...) before the root logger contains a handler, one handler is added automatically.

The trick with the global variable _LOCALS does not work for me, since the module gets imported twice with different names (one time __name__ is "logconfig" and the second time it is "myproject.logconfig"). I guess, that python thinks that both are different modules/files.

A better solution is to use the namespace of a module, that does not get imported twice with different __name__s.

Here is a better solution.

# file logconfig.py
if not hasattr(logging, "set_up_done"):
    logging.set_up_done=False

def set_up(myhome):
    if logging.set_up_done:
        return
    logging.set_up_done=True

#

emily-wong (on February 26, 2009):

I found that using the above the debug messages don't get written to log without first stopping the server.

Instead I passed the file handler back to debug function and just close the file handler each time with hdlr.close().

#

parxier (on March 21, 2009):

guettli, you can use setattr/getattr functions, this way you don't have to do initialisation of set_up_done attribute at all:

# file logconfig.py
def set_up(myhome):
    if getattr(logging, 'set_up_done', False):
        return
    setattr(logging, 'set_up_done', True)

#

Please login first before commenting.