logging into one file problem

M

Maksim Kasimov

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')
log.addHandler(hdl)



In script, which is uses these modules, I'm doing in a similar way:


in script.py:
hdl = logging.StreamHandler()
fmt = logging.Formatter("%(name)s:\t%(levelname)s:\t%(asctime)s:\t%(message)s")
hdl.setFormatter(fmt)
log = logging.getLogger('script')
log.addHandler(hdl)



Than, to direct all output into one log-file I'm doing like this:

script.py >> script.log 2>&1


All works as expected - all output in one file (script.log), but only until syslog will rotate script.log, than output to log-file stops.

How to avoid this situation?

i can't using something like this:

hdl = logging.FileHandler('script.log')

because modules are used in other scripts, and log output of each application must be in different files.

and doing in script.py like this:

module.hdl = hdl
module.log = log

will works, but it is very inconvenient, because in main script, i'm not importing all the modules (some modules imported by other modules).


thanks for help.

Python 2.2.3
FreeBSD
 
V

Vinay Sajip

Maksim Kasimov wrote:
[Example snipped]

Will the following do what you want?

Don't add handlers in each module. Just add a handler to the root
logger in the main script. Thus:

module1.py:
import logging
logger = logging.getLogger('module1')
#now use the logger in your code

module2.py:
import logging
logger = logging.getLogger('module2')
#now use the logger in your code

script.py:
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
filename='/tmp/script.log',
filemode='w') # this only works with 2.4+ - for
earlier versions, need to do as in your original post

Then, the output from loggers 'module1' and 'module2' will end up in
'/tmp/script.log' automatically.

Regards,

Vinay
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top