By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,148 Members | 774 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,148 IT Pros & Developers. It's quick & easy.

Example of how to use logging for both screen and file

P: n/a
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).

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #1
Share this Question
Share on Google+
6 Replies


P: n/a
On 22 Oct 2004 15:26:18 +0300, Ville Vainio <vi***@spammers.com> wrote:
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: ca********@gmail.com
mail: ca********@yahoo.com
Jul 18 '05 #2

P: n/a
[Ville Vainio]
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: [example snipped]
The example might not be ideal, but something like this should really
be in the module documentation.
Agreed. It's on my todo list to add more examples ...
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).

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/...l-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
Jul 18 '05 #3

P: n/a
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
Jul 18 '05 #4

P: n/a
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
Jul 18 '05 #5

P: n/a
>>>>> "Steve" == Steve <lo******@gmail.com> writes:

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).

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #6

P: n/a
Hi Ville,
On 27 Oct 2004 15:08:16 +0300, Ville Vainio <vi***@spammers.com> wrote:
>> "Steve" == Steve <lo******@gmail.com> writes:

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.SysLogH andler())
sub_component_logger.addHandler(logging.FileHandle r('/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


--
Ville Vainio http://tinyurl.com/2prnb
--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #7

This discussion thread is closed

Replies have been disabled for this discussion.