I'm using the Freebase Python library. It creates a log before executing:
self.log = logging.getLogger("freebase")
Where is this log in the file system? It's not in the executing directory or tmp.
That call does not store anything. It merely creates a logger object which can be bound and configured however you would like.
So if in your Python code, you were to add
logging.basicConfig(level=logging.WARNING)
All warnings and errors would be logged to the standard output (that's what basicConfig does), including the calls that Freebase makes. If you want to log to the filesystem or other target, you'll want to reference the logging module documentation for more information. You may also wish to reference the Logging HOWTO.
Related
How would you dynamically change the file where logs are written to in Python, using the standard logging package?
I have a single process multi-threaded application that processes tasks for specific logical bins. To help simplify debugging and searching the logs, I want each bin to have its own separate log file. Due to memory usage and scaling concerns, I don't want to split the process into multiple processes whose output I could otherwise easily redirect to a separate log. However, by default, Python's logging package only outputs to a single location, either stdout/stderr or or some other single file.
My question's similar to this question except I'm not trying to change the logging level, just the logging output destination.
you will need to create a different logger for each thread and configure each logger to it's own file.
You can call something like this function in each thread, with the appropiate bin_name:
def create_logger(bin_name, level=logging.INFO):
handler = logging.FileHandler(f'{bin_name}.log')
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
bin_logger = logging.getLogger(bin_name)
bin_logger .setLevel(level)
bin_logger .addHandler(handler)
return bin_logger
In Python, I want to optionally log from a module - but have this logging off by default, enabled with a function call. (The output from this file will be very spammy - so best off by default)
I want my code to look something like this.
log = logging.getLogger("module")
log.switch_off()
---
import module
module.log.switch_on()
I can't seem to find an option to disable a logger.
Options considered:
Using filters: I think this is a bit confusing for the client
Setting a level higher than one I use to log: (e.g. logging.CRITICAL). I don't like that we could inadvertently throw log lines into normal output if we use that level.
Use a flag and add ifs
Require the client to exclude our log events. See logging config
There are two pieces at play here. Python has logging.Logger objects and logging.Handler objects that work together to serve you logging information. Loggers handle the logic of collecting logging information, and deciding whether logs should be emitted to associated handlers. If the logging level of your log record is less severe than the level specified in the logger, it will not pass info to associated handlers.
Handlers have the same feature, and since handlers are the last line between log records and defined output, you would likely want to disable the interaction there. To accomplish this, and avoid having logs inadvertently logged elsewhere, you can add a new logging level to your application:
logging.addLevelName(logging.CRITICAL + 1, "DISABLELOGGING")
Note: This only maps the name to value for purposes of formatting, so you will need to add a member to the logging module as well:
logging.DISABLELOGGING = logging.CRITICAL + 1
Setting it to a value higher than CRITICAL ensures that no normal log event will pass and be emitted.
Then you just need to set your handler to the level you defined:
handler.setLevel(logging.DISABLELOGGING)
and now there should be no logs that pass the handler, and therefore no output shown.
I'm developing a package that will be used by others to write processing scripts. For testing/debugging/not-going-insane purposes, I'd like to include some logging statements within my code, and especially using a logging_setup() utility function that I developed for another project for formatting/file output control.
Because I'm not writing a self-contained application, however, but a library that is meant to be called by other programs, I am confused where I should use my logging_setup() utility in order to produce the desired logging results that I want. This made me wonder whether using a logging system within my package was a good idea to begin with.
Where should I use my logging_setup() utility, if anywhere?
EDIT: Here's the function I mention above:
def logging_setup(cfg_path=definitions.LOG_CONFIG_PATH, lvl=logging.INFO):
"""Setup logging tool from YAML configuration file.
This should only be run once. Formatted (or configured) logging can only be
done from within functions/classes in other modules.
"""
# create directory for log files if not already there
try:
os.makedirs(definitions.LOGS_PATH)
except OSError as e:
if e.errno != errno.EEXIST:
raise
# configure logging from yaml config file
if os.path.exists(cfg_path):
with open(cfg_path, 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
else:
logging.basicConfig(level=lvl)
Where should I use my logging_setup() utility, if anywhere?
In library code, you should not configure logging anywhere. It is up to the users of your library (application distributors) to configure logging handlers.
As a library author, you don't know anything about the runtime context, you don't even know if there is a writable filesystem available at all in order to create logfiles. But to use logging, you don't need to care about the configuration - just import logging and create loggers, at the module level, and you can log events from library code. It is not for the library code to decide where those log events go - or if they go anywhere at all.
If you're providing an app and you want logging output, then configure logging as the first thing your application does when starting up - usually in Python this means a call to logging.config.dictConfig or similar is made shortly after entering the main() function (please make sure the logging configuration does not happen at import time).
I am using the logging library in python. I am using several logger objects to output the information. I got to the point where the output is too much, and I need to send it to a logfile instead of the console.
I can't find a function that configures the output stream of the logger object, and the basicConf function doesn't seem to do the trick.
This is what I have:
import logging # Debug logging framework
logging.basicConfig(filename='loggggggmeee.txt')
logger = logging.getLogger('simulation')
logger.setLevel(logging.INFO)
#--------------- etc-------------------#
logger.info('This is sent to the console')
Any ideas? Thanks!
Try to add a file location like here it will solve your problem:
import logging # Debug logging framework
logging.basicConfig(filename='c:\\loggggggmeee.txt')
logger = logging.getLogger('simulation')
logger.setLevel(logging.INFO)
#--------------- etc-------------------#
logger.info('This is sent to the console')
By the way the file without a specific location will be at the module library...
I really recommend you to read the Logging HOWTO It's very simple and useful.
Also the Cookbook has lots of useful examples.
Another good tip about nameing the loggers from the docs:
a good convention to use when naming loggers is to use a module-level
logger, in each module which uses logging, named as follows:
logger = logging.getLogger(__name__)
This means that logger names
track the package/module hierarchy, and it’s intuitively obvious where
events are logged just from the logger name.
I'm currently working on 1.0.0 release of pyftpdlib module.
This new release will introduce some backward incompatible changes in
that certain APIs will no longer accept bytes but unicode.
While I'm at it, as part of this breackage, I was contemplating the
possibility to get rid of my logging functions, which currently use the
print statement, and use the logging module instead.
As of right now pyftpdlib delegates the logging to 3 functions:
def log(s):
"""Log messages intended for the end user."""
print s
def logline(s):
"""Log commands and responses passing through the command channel."""
print s
def logerror(s):
"""Log traceback outputs occurring in case of errors."""
print >> sys.stderr, s
The user willing to customize logs (e.g. write them to a file) is
supposed to just overwrite these 3 functions as in:
>>> from pyftpdlib import ftpserver
>>>
>>> def log2file(s):
... open('ftpd.log', 'a').write(s)
...
>>> ftpserver.log = ftpserver.logline = ftpserver.logerror = log2file
Now I'm wondering: what benefits would imply to get rid of this approach
and use logging module instead?
From a module vendor perspective, how exactly am I supposed to
expose logging functionalities in my module?
Am I supposed to do this:
import logging
logger = logging.getLogger("pyftpdlib")
...and state in my doc that "logger" is the object which is supposed
to be used in case the user wants to customize how logs behave?
Is it legitimate to deliberately set a pre-defined format output as in:
FORMAT = '[%(asctime)] %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger('pyftpdlib')
...?
Can you think of a third-party module I can take cues from where the logging functionality is exposed and consolidated as part of the public API?
Thanks in advance.
libraries (ftp server or client library) should never initialize the logging system.
So it's ok to instantiate a logger object and to point at logging.basicConfig in the
documentation (or provide a function along the lines of basicConfig with fancier output
and let the user choose among his logging configuration strategy, plain basicConfig or
library provided configuration)
frameworks (e.g. django) or servers (ftp server daemon)
should initialize the logging system to a reasonable
default and allow for customization of logging system configuration.
Typically libraries should just create a NullHandler handler, which is simply a do nothing handler. The end user or application developer who uses your library can then configure the logging system. See the section Configuring Logging for a Library in the logging documentation for more information. In particular, see the note which begins
It is strongly advised that you do not add any handlers other than NullHandler to your library's loggers.
In your case I would simply create a logging handler, as per the logging documentation,
import logging
logging.getLogger('pyftpdlib').addHandler(logging.NullHandler())
Edit The logging implementation sketched out in the question seems perfectly reasonable. In your documentation just mention logger and discuss or point users to the logging.setLevel and logging.setFormatter methods for customising the output from your library. Rather than using logging.basicConfig(format=FORMAT) you could consider using logging.config.fileConfig to manage the settings for your output and document the configuration file somewhere in your documentation, again pointing the user to the logging module documentation for the format expected in this file.
Here is a resource I used to make a customizable logger. I didn't change much, I just added an if statement, and pass in whether or not I want to log to a file or just the console.
Check this Colorer out. It's really nice for colorizing the output so DEBUG looks different than WARN which looks different than INFO.
The Logging module bundles a heck of a lot of nice functionality, like SMTP logging, file rotation logging (so you can save a couple old log files, but not make 100s of them every time something goes wrong).
If you ever want to migrate to Python 3, using the logging module will remove the need to change your print statements.
Logging is awesome depending on what you're doing, I've only lightly used it before to see where I am in a program (if you're running this function, color this way), but it has significantly more power than a regular print statement.
You can look at Django (just create a sample project) and see how it initialize logger subsystem.
There is also a contextual logger helper that I've written some time ago - this logger automatically takes name of module/class/function is was initialized from. This is very useful for debug messages where you can see right-through that module spits the messages and how the call flow goes.