简体   繁体   中英

Improving python code

I am facing the following scenario :

I set DEBUG=True/False and based on this I do the logging.

Traditional way of doing this is

if DEBUG:
   logger.log(whatever)

Is there a better way to write this code? Using closures/lambda functions etc.. ?

Look at the logging library's manual: http://docs.python.org/library/logging.html

you can configure directly in code, or in a config file ...

eg

import logging
logging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

(see how it'll only display info and warning messages)

or, from a file:

import logging
import logging.config

logging.config.fileConfig('logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

See the config section for the logging config format. http://docs.python.org/howto/logging.html#configuring-logging

The relevance of logging.getLogger(...) is that it allows you to set different log levels for different parts of your code.

Edit: if you're worried about expensive operations, it's best to use the following:

if logger.isEnabledFor(logging.DEBUG):
    logger.debug('Message with %s, %s', expensive_func1(),
                                        expensive_func2())

HTH

You are over thinking this. You have 2 lines of code that are very clear and concise. There is not much that you could do to change this without making things more complicated.

The only other short and simple way to do logging is to move the debug check into a wrapper function.

def log(msg):
  if DEBUG:
    logger.log(msg)

This will mean that the rest of your code will just have one line when logging a message. The only potential downside is that if you are building the message string, it will be built even when DEBUG is false. This is really only an issue if you need a highly efficient program and you are constructing very complicated log strings.

In this particular instance, you could consider using python's logging module, which will handle this (and other logging needs) for you. In its most basic incarnation:

# Call once somewhere early in your code
logging.basicConfig(level=DEBUG and logging.DEBUG or logging.INFO)
....

logging.debug(whatever)

One thing to watch is that 'whatever' will always get evaluated (unlike in your example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM