473,657 Members | 2,593 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to prevent logging warning?

I'm about to add some logging calls to a library I have. How can I
prevent that the script that uses the library prints
'No handlers could be found for logger "comtypes.clien t"' when the
script runs?

I would like to setup the logging so that there is no logging when
nothing is configured, and no warning messages are printed.

Thomas
Oct 5 '05 #1
10 3294

may be this you will find usefull:

def getLog(logName, fileName = None):

if fileName:
hdl = logging.FileHan dler(fileName)
else:
hdl = logging.StreamH andler()

fmt = logging.Formatt er("%(name)s:\t %(levelname)s:\ t%(asctime)s:\t %(message)s")
hdl.setFormatte r(fmt)
log = logging.getLogg er(logName)
log.addHandler( hdl)

return log
Thomas Heller wrote:
I'm about to add some logging calls to a library I have. How can I
prevent that the script that uses the library prints
'No handlers could be found for logger "comtypes.clien t"' when the
script runs?

I would like to setup the logging so that there is no logging when
nothing is configured, and no warning messages are printed.

Thomas

--
Best regards,
Maksim Kasimov
mailto: ma************@ gmail.com
Oct 5 '05 #2
> Thomas Heller wrote:
I'm about to add some logging calls to a library I have. How can I
prevent that the script that uses the library prints
'No handlers could be found for logger "comtypes.clien t"' when the
script runs?
I would like to setup the logging so that there is no logging when
nothing is configured, and no warning messages are printed.

Maksim Kasimov <ma************ @gmail.com> writes:
may be this you will find usefull:

def getLog(logName, fileName = None):

if fileName:
hdl = logging.FileHan dler(fileName)
else:
hdl = logging.StreamH andler()

fmt = logging.Formatt er("%(name)s:\t %(levelname)s:\ t%(asctime)s:\t %(message)s")
hdl.setFormatte r(fmt)
log = logging.getLogg er(logName)
log.addHandler( hdl)

return log


Not really - I know how to set up handlers, but I think it should be
optional. Assume I have

log = logging.getLogg er("comtypes.cl ient")

and later

log.warn("foo bar")

in the library code.

If I use the library an my script, I get the warning that I mentioned
above. I want the script by default to be agnostic about the libraries
logging. When I want to see the log messages, I can always do

logging.basicCo nfig()

in the script to see the log messages.

I get the behaviour that I want when I add a 'NULL' handler in the
library, but is this really how logging is intended to be used?

<library>
log = logging.getLogg er("comtypes.cl ient")

class NULLHandler(log ging.Handler):
def emit(self, *args):
pass

log.addHandler( NULLHandler())
</library>

Thomas
Oct 5 '05 #3
Thomas Heller wrote:
Thomas Heller wrote:

I'm about to add some logging calls to a library I have. How can I
prevent that the script that uses the library prints
'No handlers could be found for logger "comtypes.clien t"' when the
script runs?
I would like to setup the logging so that there is no logging when
nothing is configured, and no warning messages are printed.


Maksim Kasimov <ma************ @gmail.com> writes:
may be this you will find usefull:

def getLog(logName, fileName = None):

if fileName:
hdl = logging.FileHan dler(fileName)
else:
hdl = logging.StreamH andler()

fmt = logging.Formatt er("%(name)s:\t %(levelname)s:\ t%(asctime)s:\t %(message)s")
hdl.setFormatte r(fmt)
log = logging.getLogg er(logName)
log.addHandler( hdl)

return log


Not really - I know how to set up handlers, but I think it should be
optional. Assume I have

log = logging.getLogg er("comtypes.cl ient")

and later

log.warn("foo bar")

in the library code.

If I use the library an my script, I get the warning that I mentioned
above. I want the script by default to be agnostic about the libraries
logging. When I want to see the log messages, I can always do

logging.basicCo nfig()

in the script to see the log messages.

I get the behaviour that I want when I add a 'NULL' handler in the
library, but is this really how logging is intended to be used?

<library>
log = logging.getLogg er("comtypes.cl ient")

class NULLHandler(log ging.Handler):
def emit(self, *args):
pass

log.addHandler (NULLHandler())
</library>

Thomas

Hello,

Absolutley not, I have exactly the same problem and it is
really annoying. The logging handlers should be set from an external
config file and not explicitly in the code. I simply had to just live
with it, it's annoying but there is nothing you can do about it (short
of playing around with stdout but avoiding that is why you used logging
in the first place!).

Cheers,

Neil

--

Neil Benn
Senior Automation Engineer
Cenix BioScience
BioInnovations Zentrum
Tatzberg 46
D-01307
Dresden
Germany

Tel : +49 (0)351 4173 154
e-mail : be**@cenix-bioscience.com
Cenix Website : http://www.cenix-bioscience.com

Oct 5 '05 #4
[Thomas Heller wrote]
I'm about to add some logging calls to a library I have. How can I
prevent that the script that uses the library prints
'No handlers could be found for logger "comtypes.clien t"' when the
script runs?

I would like to setup the logging so that there is no logging when
nothing is configured, and no warning messages are printed.


This is probably a gross hack, but then I think one could argue that the
one-time "No handlers could be found for" warning is a misfeature -- at
least without a clean way to suppress it. I don't know the history of
that warning though:
-------------- mylib.py -----------------------
import logging
log = logging.getLogg er("mylib")
def func():
log.warn("don't go near the river")
log.error("I'm drowning!")
--------------------------------------------------
-------------- myscript.py -----------------------
import sys
import logging
import mylib

if __name__ == "__main__":
if "-v" in sys.argv:
logging.basicCo nfig()
else:
logging.Logger. manager.emitted NoHandlerWarnin g = True
mylib.func()
--------------------------------------------------
$ python myscript.py

$ python myscript.py -v
WARNING:mylib:d on't go near the river
ERROR:mylib:I'm drowning!
hackily yours,
Trent

--
Trent Mick
Tr****@ActiveSt ate.com
Oct 5 '05 #5
Thomas Heller wrote:
I*want*the*scri pt*by*default*t o*be*agnostic*a bout*the*librar ies
logging.**When* I*want*to*see*t he*log*messages ,*I*can*always* do

logging.basicCo nfig()

in the script to see the log messages.

I get the behaviour that I want when I add a 'NULL' handler in the
library, but is this really how logging is intended to be used?


I would support ...err, what's the opposite of a feature request?
Anyway, another hack, slightly more lightweight/intrusive:

logging.root.ma nager.emittedNo HandlerWarning = True

Peter

Oct 5 '05 #6

Thomas Heller wrote:
I get the behaviour that I want when I add a 'NULL' handler in the
library, but is this really how logging is intended to be used?


The reason for the one-off message is that without it, a
misconfiguratio n or a failure to configure any handlers is notified to
a user (who is possibly not used to the logging package). I'm not sure
which is more annoying - a one-off message which occurs when no
handlers are configured and yet events are logged, or complete silence
from logging when something is misconfigured, and not giving any
feedback on what's wrong? (It's a rhetorical question - the answer is
of course quite subjective).

Certainly, I could change things so that e.g. the error is suppressed
when logging.raiseEx ceptions is set to 0 (typically for production
use).

Regards,

Vinay Sajip

Oct 5 '05 #7
s/without/with/

Oct 5 '05 #8
"Vinay Sajip" <vi*********@ya hoo.co.uk> writes:
Thomas Heller wrote:
I get the behaviour that I want when I add a 'NULL' handler in the
library, but is this really how logging is intended to be used?

The reason for the one-off message is that without it, a
misconfiguratio n or a failure to configure any handlers is notified to
a user (who is possibly not used to the logging package). I'm not sure
which is more annoying - a one-off message which occurs when no
handlers are configured and yet events are logged, or complete silence
from logging when something is misconfigured, and not giving any
feedback on what's wrong? (It's a rhetorical question - the answer is
of course quite subjective).


I do *not* think 'no handler' is a misconfiguratio n. Is it possible to
differentiate between a misconfiguratio n and 'no configuration'?
Certainly, I could change things so that e.g. the error is suppressed
when logging.raiseEx ceptions is set to 0 (typically for production
use).


That would be fine. But there are also other ways - you could, for
example, print the warning only when __debug__ is False. And you could
use the warnings module instead of blindly printing to stderr, this way
it could also be filtered out.

BTW: Since I have your attention now, is the graphical utility to
configure the logging.conf file still available somewhere, and
compatible with the current logging package (with 'current' I mean
the one included with Python 2.3.5)?

Thomas
Oct 6 '05 #9
Thomas Heller wrote:
I do *not* think 'no handler' is a misconfiguratio n. Is it possible to
differentiate between a misconfiguratio n and 'no configuration'?
It's a fair point. The line was more blurred when the logging package
was newly released into the wild ;-) But "no configuration" could be
caused e.g. by an unreadable config file, which might also be
categorised as a "misconfigurati on".
That would be fine. But there are also other ways - you could, for
example, print the warning only when __debug__ is False. And you could
use the warnings module instead of blindly printing to stderr, this way
it could also be filtered out.
Compatibility with 1.5.2 precludes use of the warnings module. If using
raiseExceptions meets your requirement, I'll use that. I'm not sure
it's a good idea for the behaviour to change between running with and
without -O.
BTW: Since I have your attention now, is the graphical utility to
configure the logging.conf file still available somewhere, and
compatible with the current logging package (with 'current' I mean
the one included with Python 2.3.5)?


You can always get my attention via email :-) The graphical utility
(logconf.py) is available from the download at

http://www.red-dove.com/python_logging.html#download

AFAIK it should work OK with 2.3.5, though I haven't tested it recently
as there wasn't much interest in it. In fact you're the first person to
ask! It generates a few extra entries in the config file which are used
by the utility only, which are seemingly regarded as "cruft" by most
people.

Regards,
Vinay Sajip

Oct 6 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
10872
by: Ville Vainio | last post by:
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.
1
3667
by: jjesso | last post by:
I am trying to add a new logging level. logging.config.fileConfig("bengineLog.cfg") logging.CLIENT = logging.INFO + 1 logging.addLevelName( logging.CLIENT, 'CLIENT' ) logging.root.setLevel( ) logger = logging.getLogger(None) logging.Logger.client('test') I get error:
3
2462
by: Chris Smith | last post by:
Hola, pythonisas: The documentation for the logging module is good, but a bit obscure. In particular, there seems to be a lot of action at a distance. The fact that getLogger() can actually be a call to Logger.__init__(), which is mentioned in para 6.29.1, also bears stressing on 6.29. I grasp _why_ you'd implement it that way, but I may not be the only coder who feels queasy with the word 'get' being used both to fetch an instance and...
1
2263
by: Joel.Hedlund | last post by:
Hi! I'm writing a server and I want to use the logging module for logging stuff. I want to log all transactions in detail, and if everything goes haywire I want to know which client did it. Therefore I want to affix the client address to every single log item. I would like to do the following: Formatter(": %(message)s") ....
5
6077
by: Ritesh Raj Sarraf | last post by:
import os, sys, logging logger = logging.getLogger("my_app") conerr = logging.StreamHandler(sys.stderr) conerr.setLevel(logging.DEBUG) conerr_formatter = logging.Formatter('%(levelname)s %(message)s') conerr.setFormatter(conerr_formatter) console = logging.StreamHandler(sys.stdout)
3
1604
by: seb | last post by:
Hi, I am writing to a file some basic information using the logging module. It is working but in the log file some line are printed several time. I had put some print debugging messages in the logging function (so they appear on the consile) and they are called once only. Obviously there is some understantding of the logging module that I am missing. My simple logging program (see below) is called by several processes. In this way I...
3
11533
by: Chris Shenton | last post by:
I am setting up handlers to log DEBUG and above to a rotating file and ERROR and above to console. But if any of my code calls a logger (e.g., logging.error("foo")) before I setup my handlers, the logging system will create a default logger that *also* emits logs, which I can't seem to get rid of. Is there a way I can suppress the creation of this default logger, or remove it when I 'm setting up my handlers? Thanks. Sample code:
1
1931
by: ludvig.ericson | last post by:
Quote from the docs: FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" logging.basicConfig(format=FORMAT) d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} logging.warning("Protocol problem: %s", "connection reset", extra=d) would print something like
4
1617
by: samwyse | last post by:
In the Python 2.5 Library Reference, section 14.5.3 (Logging to multiple destinations), an example is given of logging to both a file and the console. This is done by using logging.basicConfig() to configure a log file, and then calling logging.getLogger('').addHandler(console) to add the console. However, in section 14.5.4 (Sending and receiving logging events across a network), a call is made to rootLogger.addHandler(socketHandler),...
0
8385
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8303
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
8723
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7316
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...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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
1601
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.