Solved

output to a text file a

Posted on 2011-09-13
8
519 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
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 500 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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
This article will show, step by step, how to integrate R code into a R Sweave document
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

749 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