Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

output to a text file a

Posted on 2011-09-13
8
Medium Priority
?
526 Views
Last Modified: 2012-05-12
I want to the logger to output to a text file and not to the screen... How can I do that

import logging, mymodule

logging.basicConfig()

log = logging.getLogger("MyApp")
log.setLevel(logging.DEBUG) #set verbosity to show all messages of severity >= DEBUG
log.info("Starting my app")
try:
    mymodule.doIt()
except Exception, e:
    log.exception("There was a problem.")
log.info("Ending my app")

Open in new window

0
Comment
Question by:dolamitejenkins
  • 4
  • 4
8 Comments
 
LVL 29

Expert Comment

by:pepr
ID: 36534274
You have to tell the filename to the logging.basicConfig().  See http://docs.python.org/howto/logging.html#logging-to-a-file

Try:
import logging

logging.basicConfig(filename='mylog.txt')

log = logging.getLogger("MyApp")
log.setLevel(logging.DEBUG) #set verbosity to show all messages of severity >= DEBUG
log.info("Starting my app")
try:
    i = 5 / 0
except Exception as e:
    log.exception("There was a problem." )
log.info("Ending my app")

Open in new window


0
 

Author Comment

by:dolamitejenkins
ID: 36536163
thanks
0
 

Author Comment

by:dolamitejenkins
ID: 36536522
Pepr When I set up my logger how do I have it record the DEBUG info for every module ?
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 29

Expert Comment

by:pepr
ID: 36538197
Frankly, I do not use the logging module, nor I did study deeply the documentation (see http://docs.python.org/howto/logging.html#logging-howto).  Because of that I can only guess what is the usual approach.  But the following worked for me...

Firstly, you can set the name of the log file in the main application only.  Notice that the import of the other modules (here moduleA) is done after that.

myApp.py
import logging
logging.basicConfig(filename='myApplog.txt')

import moduleA

def main():
    log = logging.getLogger(__name__)
    log.setLevel(logging.DEBUG) #set verbosity to show all messages in the main application
    log.info("Starting the application.")

    # Calling the module function (causes logging).
    moduleA.fn()    

    log.info("Finishing the application.")

    
if __name__ == '__main__':
    # Start the body of the application.
    main()

Open in new window


The modules also import the logging module, but they do not set the log filename:


moduleA.py
import logging

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG) #set verbosity to show all messages of severity >= DEBUG
log.info("Starting moduleA")

def fn():
    log.info("fn() called")

Open in new window


The complication is caused only by the approach when the logger (logging.getLogger()) is calling when the module is imported.  Probably more usual approach is the get the logger inside the function that wants to log via the name of the module (I will try and post later).
0
 
LVL 29

Accepted Solution

by:
pepr earned 2000 total points
ID: 36538237
Probably more realistic usage just gets the logger just before it is uses and throws it away when not needed.  You can get the same logger again based on its name.  When you always use the __name__ as the logger name, you can be sure that you will use the same logger object (i.e. severity...) inside the module.

myApp.py
import logging
import moduleA

def someFunctionInMain():
    # Get the logger just before you need it.
    log = logging.getLogger(__name__)

    # Use the logger in the app.
    log.info("someFunctionInMain() called.")



def main():
    # Setting the log filename for whole application.
    logging.basicConfig(filename='myApplog.txt')

    # Get the logger just before you need it.
    log = logging.getLogger(__name__)
    log.setLevel(logging.DEBUG) #set verbosity to show all messages in the main application
    
    # Use the logger in the app.
    log.info("Starting the application.")

    # Calling my function withou passing the logger.
    someFunctionInMain()    

    # Calling the module function (also causes logging).
    moduleA.fn()    

    # Use the logger in the app -- we still have the logger,
    # so no need to get it.
    log.info("Finishing the application.")

    
if __name__ == '__main__':
    # Start the body of the application.
    main()

Open in new window


Notice that the import commands appeared just without any commands in between.  The module will use its own logger object (possibly different severity...).

moduleA.py
import logging


def fn():
    # Getting the logger just before we need it.
    log = logging.getLogger(__name__)
    
    # ... possibly setting its verbosity.
    log.setLevel(logging.DEBUG)
    
    # Use the logger.
    log.info("fn() called")

Open in new window



After launching myApp.py, the log file contains:

INFO:__main__:Starting the application.
INFO:__main__:someFunctionInMain() called.
INFO:moduleA:fn() called
INFO:__main__:Finishing the application.

Open in new window

0
 

Author Comment

by:dolamitejenkins
ID: 36539435
thank you pepr ...
0
 

Author Closing Comment

by:dolamitejenkins
ID: 36540517
Pepr you are the best
0
 
LVL 29

Expert Comment

by:pepr
ID: 36541027
You are welcome.  And stop kidding :))  You are also the best.  You only do not know it, yet. ;)  (Part of the reason is that you still have too much hair :)
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick Powershell script I wrote to find old program installations and check versions of a specific file across the network.
Measuring Server's processing rate with a simple powershell command. The differences in processing rate also was recorded in different use-cases, when a server in free and busy states.
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Suggested Courses

963 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question