February 25, 2010
Debugging Django

Often you find yourself dealing with an error that only occurs in certain circumstances—a function might be called from dozens of different places in your program but only runs in to trouble in a very specific case. You can use the traceback module to log the current stack, which will allow you to tell how a function was called when something went wrong:

import logging, traceback, pprint    def my_buggy_function(arg):  ...  if error_condition:  stack = pprint.pformat(traceback.extract_stack())  logging.debug('An error occurred: %s' % stack)

The tuple returned by traceback.extract_stack() includes line numbers, function names and paths to Python files so you can use it to reconstruct a good amount of information about your program.

Posted via web from 原宿工業大学 | Comment »

February 24, 2010
mod_wsgi — PyAMF - AMF for Python ( ログファイルを別にする )

Create the WSGI startup file for your application in /var/www/wsgi/myApp.wsgi:

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38
import logging  from logging.handlers import RotatingFileHandler    import application as app      # logging level  LEVEL = logging.DEBUG    # a filename to append log messages to  LOG_FILENAME = '/var/log/apache2/myApp.log'    # max size in bytes before a new log file is created  MAX_SIZE = 2000    # max amount of log files before it rotates  BACKUP_COUNT = 5    # Set up a specific logger with our desired output level  logger = logging.getLogger('MyLogger')  logger.setLevel(LEVEL)    # Add the log message handler to the logger  handler = RotatingFileHandler(LOG_FILENAME,  			      maxBytes=MAX_SIZE,  			      backupCount=BACKUP_COUNT)    # log message formatter  formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s")  handler.setFormatter(formatter)  logger.addHandler(handler)      # hook up logger to gateway  app.gateway.logger = logger    # hook up gateway to mod_wsgi  application = app.gateway

Posted via web from 原宿工業大学 | Comment »

2008-05-26 - 新みのる日記 (python logging)

マイロガーとして使う

まあ、ここまでなら別になんてことはないんですが、

例えば、 warn,error,criticalはコンソールに、debug,infoはファイルに書き出すという

2種類のログを同時に取ってみる。

ソース

# encode=utf-8  import sys,os,logging    # コンソールに出力  logging.basicConfig(level=logging.WARN, format='%(asctime)s %(levelname)s %(message)s')    logging.critical('danger!!')  logging.error('ERRROR!!')  logging.warn('I am man.')  logging.info('You are man.')  logging.debug('Python!!')    # ファイルに出力  logfile = logging.FileHandler(r'C:\Mylogger.txt')  format = logging.Formatter('[%(filename)s:%(lineno)d] %(asctime)s %(levelname)s %(message)s')  logfile.setFormatter(format)  logging.getLogger('MyLogger').addHandler(logfile)  log = logging.getLogger('MyLogger')  log.setLevel(logging.DEBUG)    log.critical('MyLogger CRITICAL')  log.error('MyLogger ERROR')  log.warn('MyLogger WARN')  log.info('MyLogger INFO')  log.debug('MyLogger DEBUG')  

コンソール出力

2008-05-26 23:37:56,155 CRITICAL danger!!  2008-05-26 23:37:56,155 ERROR ERRROR!!  2008-05-26 23:37:56,171 WARNING I am man.  2008-05-26 23:37:56,171 CRITICAL MyLogger CRITICAL  2008-05-26 23:37:56,171 ERROR MyLogger ERROR  2008-05-26 23:37:56,171 WARNING MyLogger WARN  2008-05-26 23:37:56,187 INFO MyLogger INFO  2008-05-26 23:37:56,187 DEBUG MyLogger DEBUG  

ファイルの中身

[logging2-test.py:21] 2008-05-26 23:40:24,765 CRITICAL MyLogger CRITICAL  [logging2-test.py:22] 2008-05-26 23:40:24,780 ERROR MyLogger ERROR  [logging2-test.py:23] 2008-05-26 23:40:24,780 WARNING MyLogger WARN  [logging2-test.py:24] 2008-05-26 23:40:24,780 INFO MyLogger INFO  [logging2-test.py:25] 2008-05-26 23:40:24,780 DEBUG MyLogger DEBUG  

コンソールにはデフォルト(root)ロガーとMyLoggerのロガー出力がされて、

ファイルにはMyLoggerの出力のみで設定通りにうごいてるので、完了!!

Posted via web from 原宿工業大学 | Comment »

Python:logging

ログ関係のモジュールを用意する。


(djtweet)hdknr@deblen:~/.ve/djtweet/src/djcube/www/website$ more journal.py
import logging
#
def initialize():
    # apache error.log
    logging.basicConfig(level=logging.DEBUG,
                     format=’%(asctime)s %(levelname)s %(message)s’)

WSGIスクリプトとか最初に動くコードで初期化する

from app.journal import initialize
initialize()

プログラムの中で記録する

import logging
logging.debug(‘@@@’+str(type(ret))+str(ret.toPostArgs()))
mod_wsgiの場合、error.log にログされます。

Posted via email from 原宿工業大学 | Comment »

loggingモジュールで複数の出力先に別のログレベルで出力する - ytokuがつまづいた跡

しかし、それよりもbaseConfigメソッドで目についた所があった。if len(root.handlers) == 0:である。どうやらハンドラが登録されていればこのメソッドは丸ごと不要らしい。baseConfigは呼び出さなければならないという固定観念にとらわれていたが、確かに考えてみると複数ハンドラを登録して、ロガーのレベルを設定してやれば別に呼び出す必要はない。というわけで次のように書くことでやりたいことを実現できた。

import logging    logging.getLogger('').setLevel(logging.DEBUG)    logfile=logging.FileHandler("/tmp/test-logfile", "w")  logfile.setLevel(logging.INFO)  logging.getLogger('').addHandler(logfile)    console=logging.StreamHandler();  console.setLevel(logging.WARNING)  logging.getLogger('').addHandler(console)    logging.debug('A debug message')  logging.info('Some information')  logging.warning('A shot across the bows')

Posted via web from hdknr’s posterous | Comment »

January 7, 2010
ログをとる - スコトプリゴニエフスク通信

もう少し高級なやり方は、ロギング用のMiddlewareを用意すること。自分で書かなくても、例えば次の2つなどが利用できます。

開発のデバッグ用のロギングならば、断然後者をおすすめ。なぜなら、ログの内容をブラウザに出力してくれるから。

settings.pyのMIDDLEWARE_CLASSESに、djangologging.middleware.LoggingMiddlewareを追加し、

MIDDLEWARE_CLASSES = (  'django.middleware.common.CommonMiddleware',  'django.contrib.sessions.middleware.SessionMiddleware',  'django.contrib.auth.middleware.AuthenticationMiddleware',  'djangologging.middleware.LoggingMiddleware',  )  

さらに、ログの出力を許す接続先をINTERAL_IPSに設定。

INTERNAL_IPS = ('127.0.0.1',)  

あとは、通常通りloggingモジュールを使って、

from django.shortcuts import render_to_response  from django.template import RequestContext    import logging    def myview(req):  logging.error("error")  logging.warning("warning")  logging.info("info")  logging.debug("debug")  ctxt = RequestContext(req)  return render_to_response('base.html', ctxt)  

のようにすれば、このとおり。

djangologging
djangologging posted by (C)perezvon

Posted via web from hdknr’s posterous | Comment »

1:44pm  |   URL: http://hdknr.com/post/320965456
FILED UNDER: logging Python 
Bookmark and Share
December 15, 2009
loggingモジュールのあれこれ - HDEラボ

3.設定ファイルを書くときの注意

実際に私が設定ファイルを書いているときに嵌ったことをいくつかあげておきます。1. 設定ファイルには必ず “root” ロガーの設定を行う
最初から設定が行われている “root” ロガー。設定ファイルにまで書かなくてもいいだろう、その分減って見やすくなるし。
…そう思い、 “root” ロガーの設定を行わずに設定ファイルを書き、loggingの実験を行いました。
そのときの私は、まさかそんなことで2時間も悩むことになるとは思いもしませんでした。

2.args=(sys.stdout,) の ‘,’ を忘れない
インタープリタ上では
StreamHandler(sys.stdout)
で動きますが、設定ファイルに書き込む際には(sys.stdout,)としなければ
エラーになってしまいます。
タプルになるように書かないといけないのではないかと思います。実はライブラリリファレンスに書いてあることばかりだったりします。
やっぱり困ったときは基本に立ち返ることも重要ですね。

Posted via web from hdknr’s posterous | Comment »