473,721 Members | 1,835 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.getLogg er("myapp")
log.setLevel(lo gging.DEBUG)
sth = logging.StreamH andler()
sth.setLevel(lo gging.INFO)
log.addHandler( sth)
fhnd = logging.FileHan dler('/tmp/myapp.log')
fhnd.setLevel(l ogging.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 10878
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.getLogg er("myapp")
log.setLevel(lo gging.DEBUG)
sth = logging.StreamH andler()
sth.setLevel(lo gging.INFO)
log.addHandler( sth)
fhnd = logging.FileHan dler('/tmp/myapp.log')
fhnd.setLevel(l ogging.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(<ms g>)
log.error(<msg> , exception=<opti onal-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********@gmai l.com
mail: ca********@yaho o.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.basicCo nfig(level=logg ing.DEBUG,
format='%(ascti me)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.StreamH andler()
console.setLeve l(logging.INFO)
#set a format which is simpler for console use
formatter = logging.Formatt er('%(name)-12s: %(levelname)-8s
%(message)s')
#tell the handler to use this format
console.setForm atter(formatter )
#add the handler to the root logger
logging.getLogg er('').addHandl er(console)

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

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

logger1 = logging.getLogg er('myapp.area1 ')
logger2 = logging.getLogg er('myapp.area2 ')

logger1.debug(' Quick zephyrs blow, vexing daft Jim.')
logger1.info('H ow 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.handler s

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

flog.setLevel(l ogging.INFO)
slog.setLevel(l ogging.INFO)

filelog_hdlr = logging.FileHan dler('/tmp/mylog')
syslog_hdlr = logging.handler s.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.getLogg er("mylog")
Steve> slog = logging.getLogg er("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.getLogg er("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.getLogg er("mylog")
Steve> slog = logging.getLogg er("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.getLogg er("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.getLogge r('core')
sub_component_l ogger = logger.getLogge r('core.sub_com ponent')

core_app_logger .addHandler(log ging.handler.Sy sLogHandler())
sub_component_l ogger.addHandle r(logging.FileH andler('/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
1610
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 = logging.Formatter("%(name)s:\t%(levelname)s:\t%(asctime)s:\t%(message)s") hdl.setFormatter(fmt) log = logging.getLogger('module1')
3
4496
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 could be something like: Fruits Vegetables Meats Dairy
0
835
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 from time to time, and with multiple processes, it's possible to get a collision on logging. Therefore, we'd like a way to avoid this. So what I did in VB6 was that if I got an error when logging, that I'd set a counter (and allow 10 retries),...
0
1256
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 'logging' module is generally working well (even though the documentation makes me miss some proper examples how everything works together) I can't seem to close the log file again to open a new one. This is basically what I'm doing:
9
2235
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 group was into it already and is so kind to share here his experience. I have put already much efforts into this subject googling around, but up to now in vain. Best option I encountered yet is usage of the Greyware 'System Change Log' service...
6
1079
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 cheeseshop to find such a module, but came up short. I clicked on Browse Tree -Software Development but then did not see a subcategory for logging, so did not know where to look. I then typed log into the search box, but that didn't really turn...
2
2357
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 version is not important because i think most people have 5.5+ When i visit my my site with 800 x600 either by using firefox or IE, it redirects me to useie.htm. but if i use firefox with 1024 x 768, it doesnt redirect me to useie.htm. why? can...
1
1934
by: =?iso-8859-1?q?=C1lvaro_Nieto?= | last post by:
Hi I have this logging config file; ==================================================================== keys=cdmto
0
801
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 file (for example : XYZ.config) instead of the default configuration file name generated by VS2005 (app.config --> ABC.exe.config).
0
8730
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9367
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9131
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9064
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8007
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4484
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3189
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2130
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.