Example of how to use logging for both screen and file

V

Ville Vainio

Just posting this for the sake of google:

Like everyone else, I figured it's time to start using the 'logging'
module.

I typically want to dump "info" level (and up) log information to
screen, and "debug" level (and up) to a log file for in-depth
analysis. This is for scripts, so date/time/severity information is
not wanted. I assumed such a simple use case would have an example in
the docs (py 2.4), but no luck.

Here's what worked for me:

import logging

def setupLogging():
global log
log = logging.getLogger("myapp")
log.setLevel(logging.DEBUG)
sth = logging.StreamHandler()
sth.setLevel(logging.INFO)
log.addHandler(sth)
fhnd = logging.FileHandler('/tmp/myapp.log')
fhnd.setLevel(logging.DEBUG)
log.addHandler(fhnd)

setupLogging()

log.info("foo") # appears on screen and file
log.debug("bar") # appears in the file only


The example might not be ideal, but something like this should really
be in the module documentation. The example config file mostly serves
to intimidate would-be users ("I need to do *that*?!?), and many of
them probably wouldn't want to introduce a third-party wrapper module
either (I think that should be the point of the standard logging
module after all).
 
C

Carlos Ribeiro

Just posting this for the sake of google:

Like everyone else, I figured it's time to start using the 'logging'
module.

I typically want to dump "info" level (and up) log information to
screen, and "debug" level (and up) to a log file for in-depth
analysis. This is for scripts, so date/time/severity information is
not wanted. I assumed such a simple use case would have an example in
the docs (py 2.4), but no luck.

Here's what worked for me:

import logging

def setupLogging():
global log
log = logging.getLogger("myapp")
log.setLevel(logging.DEBUG)
sth = logging.StreamHandler()
sth.setLevel(logging.INFO)
log.addHandler(sth)
fhnd = logging.FileHandler('/tmp/myapp.log')
fhnd.setLevel(logging.DEBUG)
log.addHandler(fhnd)

setupLogging()

log.info("foo") # appears on screen and file
log.debug("bar") # appears in the file only

The example might not be ideal, but something like this should really
be in the module documentation. The example config file mostly serves
to intimidate would-be users ("I need to do *that*?!?), and many of
them probably wouldn't want to introduce a third-party wrapper module
either (I think that should be the point of the standard logging
module after all).

I'm also beginning to get to grips with the logging module. My first
attempt was confusing, and I ended up removing it from the code. Now I
just have a simple log method that still calls print <message>. Not
exactly what I wanted to do :p

My idea now is to write a clean and simple wrapper for the logging
module, using sensible defaults, and exposing simple methods.
Something like (still pseudo-code):

from simplelog import Logger

log = Logger(<logger-name>)
....
log.info(<msg>)
log.debug(<msg>)
log.warning(<msg>)
log.error(<msg>, exception=<optional-exception-object>)

It's a simple implementation that hides a lot of the options of the
standard logging module. Messages would be automatically written to
the most appropriate output channels, using sensible defaults. That is
more than enough for most of my logging needs. It's still in the
drawing board, though.


--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: (e-mail address removed)
mail: (e-mail address removed)
 
V

Vinay Sajip

[Ville Vainio][example snipped]

Agreed. It's on my todo list to add more examples ...

A configuration file is not really needed for simple configurations.
For the simplest usage, the minimal example at

http://www.python.org/dev/doc/devel/lib/minimal-example.html

should suffice.

[Carlos]
My idea now is to write a clean and simple wrapper for the logging
module, using sensible defaults, and exposing simple methods.
Something like (still pseudo-code):
[code snipped]

Take a look at the link above. You cannot code logging much more
simply than that.

Documentation can always be improved. Patches are always welcome! I
will look at adding Ville's simple use case to the documentation as my
next documentation activity.

Regards,


Vinay Sajip
 
V

Vinay Sajip

Here's a simple example of logging DEBUG info to file and INFO to
console. This example has been added to the documentation in CVS.

import logging

#set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s
%(message)s',
datefmt='%m-%d %H:%M',
filename='/temp/myapp.log',
filemode='w')
#define a Handler which writes INFO messages or higher to the
sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
#set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s
%(message)s')
#tell the handler to use this format
console.setFormatter(formatter)
#add the handler to the root logger
logging.getLogger('').addHandler(console)

#Now, we can log to the root logger, or any other logger. First the
root...
logging.info('Jackdaws love my big sphinx of quartz.')

#Now, define a couple of other loggers which might represent areas in
your
#application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')

leads to

10-22 22:19 root INFO Jackdaws love my big sphinx of
quartz.
10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay
from quack.
10-22 22:19 myapp.area2 ERROR The five boxing wizards jump
quickly.

in the file and

root : INFO Jackdaws love my big sphinx of quartz.
myapp.area1 : INFO How quickly daft jumping zebras vex.
myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
myapp.area2 : ERROR The five boxing wizards jump quickly.

on the console (note the absence of the DEBUG message on the console).

Regards,


Vinay Sajip
 
S

Steve

Hi list,

Could someone help me figure out what is wrong here ?? I'd like to use
logging to send logs to syslogd as well as a file. The file logging
seems to be fine, but why don't I see anything in '/var/log/messages'
??
======================================
import logging, logging.handlers

def setupLogging():
global flog, slog
flog = logging.getLogger("mylog")
slog = logging.getLogger("mylog.slog")

flog.setLevel(logging.INFO)
slog.setLevel(logging.INFO)

filelog_hdlr = logging.FileHandler('/tmp/mylog')
syslog_hdlr = logging.handlers.SysLogHandler()

flog.addHandler(filelog_hdlr)
slog.addHandler(syslog_hdlr)

setupLogging()


flog.info("##################### foo #####################")
slog.debug("################## bar ####################"")
---------------------------------------------------------------------------------------------------
my syslog.conf says:
*.* /var/log/messages
======================================


Regards
Steve
 
V

Ville Vainio

Steve> flog = logging.getLogger("mylog")
Steve> slog = logging.getLogger("mylog.slog")

I'm a logging newbie, but -

You shouldn't "get" loggers according to the "log name", but rather
the application area name. I.e.

log = logging.getLogger("myApp")

And then add different handlers to the same log object. I.e. don't
create several loggers, create several handlers for the same Logger
object, as I did in the initial example of this thread (just
substitute StreamHandler w/ sysloghandler).
 
S

Steve

Hi Ville,
Steve> flog = logging.getLogger("mylog")
Steve> slog = logging.getLogger("mylog.slog")

I'm a logging newbie, but -

You shouldn't "get" loggers according to the "log name", but rather
the application area name. I.e.

log = logging.getLogger("myApp")

And then add different handlers to the same log object. I.e. don't
create several loggers, create several handlers for the same Logger
object, as I did in the initial example of this thread (just
substitute StreamHandler w/ sysloghandler).
I do understand that. The code above was just an example. What I
do want is, different loggers for different areas of the application.
let me explain that.
All the components in the system would have to log to syslog,
some components additionally would log to other places (like files).
So, for example:

core_app_logger = logger.getLogger('core')
sub_component_logger = logger.getLogger('core.sub_component')

core_app_logger.addHandler(logging.handler.SysLogHandler())
sub_component_logger.addHandler(logging.FileHandler('/tmp/sub_comp_log")

Now, because of the way logging is designed, any message sent to
sub_component would also get handled by the core-logger's handler
(SysLogHandler). ....or so it would seem ...I still haven't got the
SysLogHandler working :(


Regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top