If you're not used to work with the standard module logging, this snippet will allow you to incorporate a logger in your application without effort. It gives you a starting point before you try to use more sophisticated features of the logging module.
Log to a file, now !
#!/usr/bin/env python
"""
Module simplelog :
provides immediate logging to a text file (using module logging)
Usage:
from simplelog import *
log = getSimpleLogger("myPath/myFile.txt")
log.info("an example message")
Remark:
getSimpleLogger can be called multiple times with the same
filename. It identifies the logger with the file's basename,
so you can't have 2 different loggers named myFile.txt (even
in different folders.)
"""
import logging
import os .path
__all__ =["getSimpleLogger"]
_loggers ={}
def getSimpleLogger (pathToFile ):
"returns a logger to the given file"
name =os .path .basename (pathToFile )
theLogger =logging .getLogger (name )
if name in _loggers :
return theLogger
_loggers [name ]=True
theLogger .setLevel (logging .DEBUG )
theHandler =logging .FileHandler (pathToFile ,'w')
theFormatter =logging .Formatter (
"%(asctime)s %(levelname)-8s %(message)s",
"%H:%M:%S",
#"%a, %d %b %Y %H:%M:%S",
)
theHandler .setFormatter (theFormatter )
theLogger .addHandler (theHandler )
return theLogger
if __name__ =="__main__":
logger =getSimpleLogger ("foo.txt")
for i in range (20 ):
logger .info ("current index is %d"%i )
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.