简体   繁体   中英

writing a log file from python program

I want to output some strings to a log file and I want the log file to be continuously updated.

I have looked into the logging module pf python and found out that it is mostly about formatting and concurrent access.

Please let me know if I am missing something or amy other way of doing it

usually i do the following:

  # logging  
  LOG = "/tmp/ccd.log"                                                     
  logging.basicConfig(filename=LOG, filemode="w", level=logging.DEBUG)  

  # console handler  
  console = logging.StreamHandler()  
  console.setLevel(logging.ERROR)  
  logging.getLogger("").addHandler(console)

The logging part initialises logging's basic configurations . In the following I set up a console handler that prints out some logging information separately. Usually my console output is set to output only errors (logging.ERROR) and the detailed output in the LOG file.

Your loggings will now printed to file. For instance using:

logger = logging.getLogger(__name__)
logger.debug("hiho debug message")

or even

logging.debug("next line")

should work.

Doug Hellmann has a nice guide .

To add my 10cents with regards to using logging. I've only recently discovered the Logging module and was put off at first. Maybe just because it initially looks like a lot of work, but it's really simple and incredibly handy.

This is the set up that I use. Similar to Mkinds answer, but includes a timestamp.

# Set up logging
log = "bot.log"
logging.basicConfig(filename=log,level=logging.DEBUG,format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S')
logging.info('Log Entry Here.')

Which will produce something like:

22/09/2015 14:39:34 Log Entry Here.

You can log to a file with the Logging API.

Example: http://docs.python.org/2/howto/logging.html#logging-to-a-file

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