Solved

output to a text file a

Posted on 2011-09-13
8
523 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
The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

 
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

Application Discovery Service in AWS

In the era of the cloud, customers migrating away from their existing on-premise infrastructure. This requires lots of planning, strategies, and effort to identify their existing resources and determine how best to migrate.  Datacenter migrations happen in four phases -

Question has a verified solution.

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

A set of related code is known to be a Module, it helps us to organize our code logically which is much easier for us to understand and use it. Module is an object with arbitrarily named attributes which can be used in binding and referencing. …
In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

628 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