473,396 Members | 1,990 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Example of how to use logging for both screen and file

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
6 10854
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
[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
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
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
>>>>> "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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Maksim Kasimov | last post by:
hello in my modules, I'm using logging module, doing thus (there is a few modules): in module1.py: hdl = logging.StreamHandler() fmt =...
3
by: VB Programmer | last post by:
A dropdownlist in my ASP.NET webform needs to be populated from values taken from an XML file. Can someone provide a (simple) sample XML file and a parsing routine using VB.NET? The values...
0
by: HockeyFan | last post by:
I am new to .Net and kinda thrown into it. I've done this in VB6, but would like to see code, or at least a skeleton of how to more elegantly do this same thing in VB.Net. We log to an XML file...
0
by: Christoph Haas | last post by:
Evening, I have an application that is running in an endless loop processing an incoming queue. Every run is supposed to write a log file about the run and then close it again. While the...
9
by: Claudio Grondi | last post by:
I am aware, that it is maybe the wrong group to ask this question, but as I would like to know the history of past file operations from within a Python script I see a chance, that someone in this...
6
by: metaperl | last post by:
Hello, I am looking for a module which has * log levels * output to stdout and file (either/or based on config) * nicely formatted log output (e.g., indentation when appropriate) I tried to use...
2
by: one.1more | last post by:
Hello, I have the following code but its not working. i want my site to be accessible only if the visitors resolution is 1024 x 768 or higher and only if they are using internet explorer. the...
1
by: =?iso-8859-1?q?=C1lvaro_Nieto?= | last post by:
Hi I have this logging config file; ==================================================================== keys=cdmto
0
by: =?Utf-8?B?Si4gUmF5bW9uZA==?= | last post by:
Hi, Is it possible to specify a configuration file other than the default «ABC.exe.config»? In others words, I would like the application logging block to use a customized configuration...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.