Popular recipes tagged "logging"http://code.activestate.com/recipes/tags/logging/2016-05-27T01:07:42-07:00ActiveState Code RecipesJSON Formatted Logging (Python)
2016-05-27T01:07:42-07:00Michael Blan Palmerhttp://code.activestate.com/recipes/users/4194130/http://code.activestate.com/recipes/580667-json-formatted-logging/
<p style="color: grey">
Python
recipe 580667
by <a href="/recipes/users/4194130/">Michael Blan Palmer</a>
(<a href="/recipes/tags/json/">json</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/python/">python</a>).
</p>
<p>I have created a package that outputs JSON formatted lines to a log file. It can make use of the standard logging parameters and/or take custom input. The use of JSON in the log file allows for easy filtering and processing.</p>
Set the logging level to every logger (Python)
2015-10-28T23:16:26-07:00Tim McNamarahttp://code.activestate.com/recipes/users/4193044/http://code.activestate.com/recipes/579119-set-the-logging-level-to-every-logger/
<p style="color: grey">
Python
recipe 579119
by <a href="/recipes/users/4193044/">Tim McNamara</a>
(<a href="/recipes/tags/configuration/">configuration</a>, <a href="/recipes/tags/logging/">logging</a>).
</p>
<p>Python's logging allocates a name to every logger. That makes it hard to do something like, setting everything to <code>logging.ERROR</code>. Here's one way you might go about that:</p>
Amazon SNS handler for the logging module (Python)
2014-11-06T17:32:26-08:00Andrea Corbellinihttp://code.activestate.com/recipes/users/4186880/http://code.activestate.com/recipes/578956-amazon-sns-handler-for-the-logging-module/
<p style="color: grey">
Python
recipe 578956
by <a href="/recipes/users/4186880/">Andrea Corbellini</a>
(<a href="/recipes/tags/aws/">aws</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/sns/">sns</a>).
Revision 2.
</p>
<p>This is a handler for the standard <a href="https://docs.python.org/library/logging.html">logging</a> module that sends notifications to the <a href="http://aws.amazon.com/sns/">Amazon Simple Notification Service</a>.</p>
<p>You can use it like so:</p>
<pre class="prettyprint"><code>logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d '
'%(thread)d %(message)s',
},
'simple': {
'format': '%(levelname)s %(message)s',
},
},
'handlers': {
'sns': {
'level': 'INFO',
'class': 'SNSHandler',
'formatter': 'verbose',
'topic_arn': 'YOUR SNS TOPIC ARN',
},
},
'loggers': {
'YOUR MODULE': {
'handlers': ['sns'],
'level': 'INFO',
'propagate': True,
},
},
}
</code></pre>
NondurableLogger class for use with concurrent.futures.ProcessPoolExecutor's submit and map methods (Python)
2014-02-10T17:50:59-08:00Peter Santorohttp://code.activestate.com/recipes/users/4189027/http://code.activestate.com/recipes/578827-nondurablelogger-class-for-use-with-concurrentfutu/
<p style="color: grey">
Python
recipe 578827
by <a href="/recipes/users/4189027/">Peter Santoro</a>
(<a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/multiprocessing/">multiprocessing</a>).
Revision 2.
</p>
<p>I needed a simple logging solution that I could use with with concurrent.futures.ProcessPoolExecutor and this is my initial recipe.</p>
Log watcher (tail -F *.log) (Python)
2014-04-04T15:54:03-07:00Giampaolo RodolĂ http://code.activestate.com/recipes/users/4178764/http://code.activestate.com/recipes/577968-log-watcher-tail-f-log/
<p style="color: grey">
Python
recipe 577968
by <a href="/recipes/users/4178764/">Giampaolo RodolĂ </a>
(<a href="/recipes/tags/color/">color</a>, <a href="/recipes/tags/log/">log</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/monitor/">monitor</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/rotate/">rotate</a>, <a href="/recipes/tags/rotations/">rotations</a>, <a href="/recipes/tags/tail/">tail</a>).
Revision 10.
</p>
<p>A python class which "watches" a directory and calls a callback(filename, lines) function every time one of the files being watched gets written, in real time.</p>
<p>Practically speaking, this can be compared to <em>"tail -F *.log"</em> UNIX command, but instead of having lines printed to stdout a python function gets called.</p>
<p>Similarly to tail, it takes care of "watching" new files which are created after initialization and "unwatching" those ones which are removed in the meantime. This means you'll be able to "follow" and support also rotating log files.</p>
<p><strong>History</strong></p>
<ul>
<li>rev5 (2013-04-05):
<ul>
<li>sizehint parameter</li>
</ul></li>
<li>rev4 (2013-03-16):
<ul>
<li>python 3 support (also dropped support for python <= 2.5)</li>
<li>windows support</li>
<li>unit tests</li>
<li>main class can also be used as a context manager</li>
</ul></li>
<li>rev3 (2012-01-13): initial release</li>
</ul>
Get full caller name (package.module.function) (Python)
2012-11-30T21:54:46-08:00anatoly techtonikhttp://code.activestate.com/recipes/users/4168147/http://code.activestate.com/recipes/578352-get-full-caller-name-packagemodulefunction/
<p style="color: grey">
Python
recipe 578352
by <a href="/recipes/users/4168147/">anatoly techtonik</a>
(<a href="/recipes/tags/caller/">caller</a>, <a href="/recipes/tags/debug/">debug</a>, <a href="/recipes/tags/logging/">logging</a>).
</p>
<p>This function allows to get fully qualified name of the calling function. I expected this field to be available from logging module, but it is not here <a href="http://docs.python.org/2/library/logging.html#logrecord-attributes" rel="nofollow">http://docs.python.org/2/library/logging.html#logrecord-attributes</a> It might be that it is too expensive for performance or just doesn't play well in some situations. I don't know. I use it solely when debugging and it is convenient.</p>
<p>Also here: <a href="https://gist.github.com/2151727" rel="nofollow">https://gist.github.com/2151727</a></p>
Print Logger Internals (Python)
2012-12-24T04:11:35-08:00Dave Baileyhttp://code.activestate.com/recipes/users/4168479/http://code.activestate.com/recipes/578389-print-logger-internals/
<p style="color: grey">
Python
recipe 578389
by <a href="/recipes/users/4168479/">Dave Bailey</a>
(<a href="/recipes/tags/logging/">logging</a>).
</p>
<p>This helper function simplifies the difficult task of setting up and maintaining a logging system. Changes to a logging system can cause unanticipated consequences such as lost messages or duplicates. Debugging a logging hierarchy can be a tedious task. This function overrides the internal __repr__ functions of the internal classes and allows a print statement to generate the complete logger hierarchy with its associated internals. It allows easy debugging a logger and allows changes to be easily detected.</p>
Simple creation, configuration and installation of logging handlers (Python)
2011-06-01T19:05:40-07:00Hankhttp://code.activestate.com/recipes/users/4178168/http://code.activestate.com/recipes/577731-simple-creation-configuration-and-installation-of-/
<p style="color: grey">
Python
recipe 577731
by <a href="/recipes/users/4178168/">Hank</a>
(<a href="/recipes/tags/logging/">logging</a>).
</p>
<p>A helper class and function to make it easy to configure logging, and an example of using it to send <code>INFO</code> to <code>sys.stdout</code> and <code>WARNING</code> or above to <code>sys.stderr</code>.</p>
<p>This is a simple port to Python 2 (I tested on 2.7) of <a href="http://code.activestate.com/recipes/577496-simple-creation-configuration-and-installation-of-/">Nick Coghlan's Python 3 recipe</a> for doing the same thing.</p>
easy logging with extras (Python)
2010-11-02T10:04:15-07:00Bud P. Brueggerhttp://code.activestate.com/recipes/users/4175472/http://code.activestate.com/recipes/577448-easy-logging-with-extras/
<p style="color: grey">
Python
recipe 577448
by <a href="/recipes/users/4175472/">Bud P. Bruegger</a>
(<a href="/recipes/tags/logging/">logging</a>).
</p>
<p>The logging package offers the "extra" keyword argument in Logger.log to add user-defined attributes to the log record. LoggerAdaptors make it easy to use extras that are constant for a given logger; then simply use logger.debug, logger.info, ecc. But this won't support variable extra arguments. </p>
<p>The present recipe makes it easy to use "extra" attributes that are not constant but variables passed to the (modified) logging methods ('debug', 'info', ...)</p>
Simple creation, configuration and installation of logging handlers (Python)
2011-06-01T12:13:21-07:00Nick Coghlanhttp://code.activestate.com/recipes/users/2035254/http://code.activestate.com/recipes/577496-simple-creation-configuration-and-installation-of-/
<p style="color: grey">
Python
recipe 577496
by <a href="/recipes/users/2035254/">Nick Coghlan</a>
(<a href="/recipes/tags/logging/">logging</a>).
</p>
<p>Creation of log message handler for the logging module is often a multi-step process, involving creation of the handler object, configuration of the message levels and formats, installation of any filters and then actual connection of the handler to the relevant logger object.</p>
<p>This helper function allows all of these things to be specified up front in a single function call, which then takes care of configuring the handler object appropriately.</p>
Better quote module for bash shells (Python)
2010-12-03T09:16:45-08:00Kevin L. Sitzehttp://code.activestate.com/recipes/users/4173535/http://code.activestate.com/recipes/577483-better-quote-module-for-bash-shells/
<p style="color: grey">
Python
recipe 577483
by <a href="/recipes/users/4173535/">Kevin L. Sitze</a>
(<a href="/recipes/tags/bash/">bash</a>, <a href="/recipes/tags/command/">command</a>, <a href="/recipes/tags/commandline/">commandline</a>, <a href="/recipes/tags/escape/">escape</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/quote/">quote</a>, <a href="/recipes/tags/script/">script</a>, <a href="/recipes/tags/shell/">shell</a>).
</p>
<p>This Python module quotes a Python string so that it will be treated as a single argument to commands ran via os.system() (assuming bash is the underlying shell). In other words, this module makes arbitrary strings "command line safe" (for bash command lines anyway, YMMV if you're using Windows or one of the (less fine) posix shells).</p>
Logging asserts (Python)
2010-03-01T03:22:43-08:00d.schlabinghttp://code.activestate.com/recipes/users/4168903/http://code.activestate.com/recipes/577074-logging-asserts/
<p style="color: grey">
Python
recipe 577074
by <a href="/recipes/users/4168903/">d.schlabing</a>
(<a href="/recipes/tags/logging/">logging</a>).
Revision 2.
</p>
<p>This tries to marry assert statements with logging. If you use asserts together with logging and the script stops because an assertion is not fulfilled, you will not find any information about this in the logs.
Unless you do something like this:</p>
<pre class="prettyprint"><code>meal = ["eggs", "bacon", "spam"]
try:
assert "spam" not in meal, "But I don't like spam!"
except AssertionError:
log.exception("But I don't like spam!")
raise
</code></pre>
<p>With the proposed recipe a somewhat similar behaviour can be achieved by:</p>
<pre class="prettyprint"><code>log_assert("spam" not in meal, "But I don't like spam!")
</code></pre>
Tiny trace/debug-logging tool with smart event filtering (Python)
2011-04-29T02:23:37-07:00Jan Kaliszewskihttp://code.activestate.com/recipes/users/4172762/http://code.activestate.com/recipes/577429-tiny-tracedebug-logging-tool-with-smart-event-filt/
<p style="color: grey">
Python
recipe 577429
by <a href="/recipes/users/4172762/">Jan Kaliszewski</a>
(<a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/trace/">trace</a>).
Revision 3.
</p>
<ul>
<li><p>Just import, call and log your selected call/return/exception/etc. events.</p></li>
<li><p>You can use a standard Python logger from the <code>logging</code> module.</p></li>
<li><p>Quite flexible tool and about 50 efective SLOC only (excluding the example script).</p></li>
<li><p>For debugging rather than production environments (programs noticeably slow down).</p></li>
</ul>
logging support for python daemon (Python)
2010-10-25T15:22:18-07:00Bud P. Brueggerhttp://code.activestate.com/recipes/users/4175472/http://code.activestate.com/recipes/577442-logging-support-for-python-daemon/
<p style="color: grey">
Python
recipe 577442
by <a href="/recipes/users/4175472/">Bud P. Bruegger</a>
(<a href="/recipes/tags/daemon/">daemon</a>, <a href="/recipes/tags/logging/">logging</a>).
</p>
<p>The recipe shows how to subclass python-daemon's [1] DaemonContext to add logging support. In particular, it is possible to ask to keep the files related to a list of loggers (loggers_preserve) open and to redirect stdout and stderr to a logger (e.g., one using a RotatingFileHandler). </p>
<p>[1] See <a href="http://pypi.python.org/pypi/python-daemon/" rel="nofollow">http://pypi.python.org/pypi/python-daemon/</a></p>
LoggingWebMonitor - a central logging server and monitor. (Python)
2010-02-02T01:56:42-08:00Gabriel Genellinahttp://code.activestate.com/recipes/users/924636/http://code.activestate.com/recipes/577025-loggingwebmonitor-a-central-logging-server-and-mon/
<p style="color: grey">
Python
recipe 577025
by <a href="/recipes/users/924636/">Gabriel Genellina</a>
(<a href="/recipes/tags/client_server/">client_server</a>, <a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/distributed/">distributed</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/remote/">remote</a>, <a href="/recipes/tags/sysadmin/">sysadmin</a>, <a href="/recipes/tags/web/">web</a>).
Revision 3.
</p>
<p>LoggingWebMonitor listens for log records sent from other processes running in the same box or network. Collects and saves them concurrently in a log file. Shows a summary web page with the latest N records received.</p>
Multiprocess-safe logging file-handler + interprocess RLock (Python)
2010-09-22T17:30:10-07:00Jan Kaliszewskihttp://code.activestate.com/recipes/users/4172762/http://code.activestate.com/recipes/577395-multiprocess-safe-logging-file-handler-interproces/
<p style="color: grey">
Python
recipe 577395
by <a href="/recipes/users/4172762/">Jan Kaliszewski</a>
(<a href="/recipes/tags/concurrency/">concurrency</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/file_lock/">file_lock</a>, <a href="/recipes/tags/flock/">flock</a>, <a href="/recipes/tags/handler/">handler</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/process/">process</a>, <a href="/recipes/tags/rlock/">rlock</a>, <a href="/recipes/tags/threading/">threading</a>, <a href="/recipes/tags/threadsafe/">threadsafe</a>).
Revision 11.
</p>
<p>A Python 2.x/3.x-compatibile <strong>multiprocess-safe logging file-handler</strong> (logging.FileHandler replacement, designed for logging to a single file from multiple independent processes) together with a simple <strong>interprocess recursive lock</strong> -- universal abstract classes + Unix/Linux implementation.</p>
<p><strong>Update:</strong> It's is a deeply revised version. Especially, now it --</p>
<ul>
<li>is Python 2.4, 2.5, 2.6, 3.1 -compatibile (previously Py>=2.6 was needed); probably works also with 2.7, 3.0 and 3.2 (but not tested if it does);</li>
<li>is multiprocess-safe as well as thread-safe (proviously thread safety within a process was missed);</li>
<li>is based on public interfaces only (previously FileHandler._open() was called and overriden);</li>
<li>implement full RLock instance interface, as documented for threading.RLock (previously non-blocking mode and context-manager interface were missing).</li>
</ul>
<p>The module contains:</p>
<ul>
<li>Unix/Linux-only example implementation (with flock-based locking):
<strong>FLockRLock</strong> and <strong>FLockFileHandler</strong> classes.</li>
<li>universal abstract classes -- which may be useful at developing implementation for non-Unix platforms:
<strong>MultiprocessRLock</strong>, <strong>MultiprocessFileHandler</strong>, <strong>LockedFileHandler</strong>,</li>
</ul>
<p>Also a quick-and-dirty test was added.</p>
<p><strong>It is still an alpha version -- I'll be very grateful for any feedback.</strong></p>
<hr />
<p><strong>Further updates:</strong></p>
<ul>
<li><p>2010-09-20: Some corrections, especially: non-blocking mode bug in MultiprocessRLock.acquire() fixed; _test() function improved; plus fixes in the description below.</p></li>
<li><p>2010-09-22: _test() improved and moved to description section. Mistaken copyright-notice removed.</p></li>
</ul>
node.js quicklog method to log to a file (JavaScript)
2010-08-11T05:08:57-07:00Trent Mickhttp://code.activestate.com/recipes/users/4173505/http://code.activestate.com/recipes/577351-nodejs-quicklog-method-to-log-to-a-file/
<p style="color: grey">
JavaScript
recipe 577351
by <a href="/recipes/users/4173505/">Trent Mick</a>
(<a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/nodejs/">nodejs</a>).
</p>
<p>I tend to have a "quicklog" method for a few of the languages I'm working in to do logging when stdout/stderr isn't necessarily available (GUI app) or convenient (lots of other output on stdout, etc.). My usage with <a href="http://nodejs.org">nodejs</a> was while working on the node REPL. Log output to stdout interfered with the REPL.</p>
Python script main line for graceful exception handling and logging (Python)
2010-09-11T05:46:59-07:00Trent Mickhttp://code.activestate.com/recipes/users/4173505/http://code.activestate.com/recipes/577258-python-script-main-line-for-graceful-exception-han/
<p style="color: grey">
Python
recipe 577258
by <a href="/recipes/users/4173505/">Trent Mick</a>
(<a href="/recipes/tags/error/">error</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/main/">main</a>, <a href="/recipes/tags/mainline/">mainline</a>, <a href="/recipes/tags/script/">script</a>).
Revision 5.
</p>
<p>This is a recipe is often use for the mainline of my Python scripts. With this recipe your Python script will:</p>
<ul>
<li>gracefully handle <code>Ctrl+C</code> (i.e. <code>KeyboardInterrupt</code>)</li>
<li>log an error (using the <code>logging</code> module) for uncaught exceptions, importantly <strong>with the file and line number</strong> in your Python code where the exception was raised</li>
<li>gracefully ignore a closed output pipe (common when the user pipes your script through <code>less</code> and terminates that)</li>
<li>if your script logger is enabled for <code>DEBUG</code> level logging, a full traceback will be shown for an uncaught exception</li>
</ul>
<p>Presumptions:</p>
<ul>
<li><p>you have a global <code>log</code> variable a la:</p>
<pre class="prettyprint"><code>import logging
log = logging.setLevel("scriptname")
</code></pre></li>
<li><p>your script's entry point is a function <code>def main(argv): ...</code></p></li>
</ul>
Use DebugView utility with standard python logging (Python)
2010-02-10T10:35:59-08:00Christopher Prinoshttp://code.activestate.com/recipes/users/481494/http://code.activestate.com/recipes/577040-use-debugview-utility-with-standard-python-logging/
<p style="color: grey">
Python
recipe 577040
by <a href="/recipes/users/481494/">Christopher Prinos</a>
(<a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/debugview/">debugview</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/sysinternals/">sysinternals</a>, <a href="/recipes/tags/windows/">windows</a>).
</p>
<p>This is a custom logging.Handler class that lets you use standard logging calls to output messages to SysInternals' DebugView utility.</p>
Easy Exception, Error Handling and Debugging with Auto Logging (Python)
2010-04-06T20:40:05-07:00AJ. Mayorgahttp://code.activestate.com/recipes/users/4173476/http://code.activestate.com/recipes/577144-easy-exception-error-handling-and-debugging-with-a/
<p style="color: grey">
Python
recipe 577144
by <a href="/recipes/users/4173476/">AJ. Mayorga</a>
(<a href="/recipes/tags/debug/">debug</a>, <a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/error_propagation/">error_propagation</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/logging/">logging</a>).
Revision 5.
</p>
<p>Being new to Python and trying to chase where in my project exceptions were taking place always seems to take up a large amount of time. So I created this class that I now pretty use in all my projects to help me save time tracking exceptions and errors. its also has the ability to generate error logs or to output SQL query and data tuples for Database logging. Ive added sample code to give you an idea of how I normally use it. Hope this helps its saved me hours in tracking error/exception. Feed back would be great, mind you havent been Python all that long</p>