# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # mollinaca, 2021 # 渋川よしき , 2022 # tomo, 2022 # TENMYO Masakazu, 2024 # Takeshi Nakazato, 2024 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.14\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-05-08 02:53-0300\n" "PO-Revision-Date: 2021-06-28 00:53+0000\n" "Last-Translator: Takeshi Nakazato, 2024\n" "Language-Team: Japanese (https://app.transifex.com/python-doc/teams/5390/" "ja/)\n" "Language: ja\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../howto/logging-cookbook.rst:5 msgid "Logging Cookbook" msgstr "Logging クックブック" #: ../../howto/logging-cookbook.rst:0 msgid "Author" msgstr "著者" #: ../../howto/logging-cookbook.rst:7 msgid "Vinay Sajip " msgstr "Vinay Sajip " #: ../../howto/logging-cookbook.rst:9 msgid "" "This page contains a number of recipes related to logging, which have been " "found useful in the past. For links to tutorial and reference information, " "please see :ref:`cookbook-ref-links`." msgstr "" "このページは、過去に有用であるとされていた、logging に関連するいくつものレシ" "ピを含んでいます。チュートリアルやリファレンス情報へのリンクについては :ref:" "`cookbook-ref-links` を参照してください。" #: ../../howto/logging-cookbook.rst:16 msgid "Using logging in multiple modules" msgstr "複数のモジュールで logging を使う" #: ../../howto/logging-cookbook.rst:18 msgid "" "Multiple calls to ``logging.getLogger('someLogger')`` return a reference to " "the same logger object. This is true not only within the same module, but " "also across modules as long as it is in the same Python interpreter " "process. It is true for references to the same object; additionally, " "application code can define and configure a parent logger in one module and " "create (but not configure) a child logger in a separate module, and all " "logger calls to the child will pass up to the parent. Here is a main " "module::" msgstr "" "``logging.getLogger('someLogger')`` の複数回の呼び出しは同じ logger への参照" "を返します。これは同じ Python インタプリタプロセス上で動いている限り、一つの" "モジュールの中からに限らず、モジュールをまたいでも当てはまります。同じオブ" "ジェクトへの参照という点でも正しいです。さらに、一つのモジュールの中で親 " "logger を定義して設定し、別のモジュールで子 logger を定義する (ただし設定はし" "ない) ことが可能で、すべての子 logger への呼び出しは親にまで渡されます。まず" "はメインのモジュールです::" #: ../../howto/logging-cookbook.rst:26 msgid "" "import logging\n" "import auxiliary_module\n" "\n" "# create logger with 'spam_application'\n" "logger = logging.getLogger('spam_application')\n" "logger.setLevel(logging.DEBUG)\n" "# create file handler which logs even debug messages\n" "fh = logging.FileHandler('spam.log')\n" "fh.setLevel(logging.DEBUG)\n" "# create console handler with a higher log level\n" "ch = logging.StreamHandler()\n" "ch.setLevel(logging.ERROR)\n" "# create formatter and add it to the handlers\n" "formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " "%(message)s')\n" "fh.setFormatter(formatter)\n" "ch.setFormatter(formatter)\n" "# add the handlers to the logger\n" "logger.addHandler(fh)\n" "logger.addHandler(ch)\n" "\n" "logger.info('creating an instance of auxiliary_module.Auxiliary')\n" "a = auxiliary_module.Auxiliary()\n" "logger.info('created an instance of auxiliary_module.Auxiliary')\n" "logger.info('calling auxiliary_module.Auxiliary.do_something')\n" "a.do_something()\n" "logger.info('finished auxiliary_module.Auxiliary.do_something')\n" "logger.info('calling auxiliary_module.some_function()')\n" "auxiliary_module.some_function()\n" "logger.info('done with auxiliary_module.some_function()')" msgstr "" #: ../../howto/logging-cookbook.rst:56 msgid "Here is the auxiliary module::" msgstr "そして補助モジュール (auxiliary module) がこちらです::" #: ../../howto/logging-cookbook.rst:58 msgid "" "import logging\n" "\n" "# create logger\n" "module_logger = logging.getLogger('spam_application.auxiliary')\n" "\n" "class Auxiliary:\n" " def __init__(self):\n" " self.logger = logging.getLogger('spam_application.auxiliary." "Auxiliary')\n" " self.logger.info('creating an instance of Auxiliary')\n" "\n" " def do_something(self):\n" " self.logger.info('doing something')\n" " a = 1 + 1\n" " self.logger.info('done doing something')\n" "\n" "def some_function():\n" " module_logger.info('received a call to \"some_function\"')" msgstr "" #: ../../howto/logging-cookbook.rst:76 msgid "The output looks like this:" msgstr "出力はこのようになります:" #: ../../howto/logging-cookbook.rst:78 msgid "" "2005-03-23 23:47:11,663 - spam_application - INFO -\n" " creating an instance of auxiliary_module.Auxiliary\n" "2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -\n" " creating an instance of Auxiliary\n" "2005-03-23 23:47:11,665 - spam_application - INFO -\n" " created an instance of auxiliary_module.Auxiliary\n" "2005-03-23 23:47:11,668 - spam_application - INFO -\n" " calling auxiliary_module.Auxiliary.do_something\n" "2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -\n" " doing something\n" "2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -\n" " done doing something\n" "2005-03-23 23:47:11,670 - spam_application - INFO -\n" " finished auxiliary_module.Auxiliary.do_something\n" "2005-03-23 23:47:11,671 - spam_application - INFO -\n" " calling auxiliary_module.some_function()\n" "2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -\n" " received a call to 'some_function'\n" "2005-03-23 23:47:11,673 - spam_application - INFO -\n" " done with auxiliary_module.some_function()" msgstr "" #: ../../howto/logging-cookbook.rst:102 msgid "Logging from multiple threads" msgstr "複数のスレッドからのロギング" #: ../../howto/logging-cookbook.rst:104 msgid "" "Logging from multiple threads requires no special effort. The following " "example shows logging from the main (initial) thread and another thread::" msgstr "" "複数スレッドからのロギングでは特別に何かをする必要はありません。\n" "次の例はmain (初期) スレッドとそれ以外のスレッドからのロギングの例です::" #: ../../howto/logging-cookbook.rst:107 msgid "" "import logging\n" "import threading\n" "import time\n" "\n" "def worker(arg):\n" " while not arg['stop']:\n" " logging.debug('Hi from myfunc')\n" " time.sleep(0.5)\n" "\n" "def main():\n" " logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d " "%(threadName)s %(message)s')\n" " info = {'stop': False}\n" " thread = threading.Thread(target=worker, args=(info,))\n" " thread.start()\n" " while True:\n" " try:\n" " logging.debug('Hello from main')\n" " time.sleep(0.75)\n" " except KeyboardInterrupt:\n" " info['stop'] = True\n" " break\n" " thread.join()\n" "\n" "if __name__ == '__main__':\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:133 msgid "When run, the script should print something like the following:" msgstr "実行すると、出力は以下のようになるはずです:" #: ../../howto/logging-cookbook.rst:135 msgid "" " 0 Thread-1 Hi from myfunc\n" " 3 MainThread Hello from main\n" " 505 Thread-1 Hi from myfunc\n" " 755 MainThread Hello from main\n" "1007 Thread-1 Hi from myfunc\n" "1507 MainThread Hello from main\n" "1508 Thread-1 Hi from myfunc\n" "2010 Thread-1 Hi from myfunc\n" "2258 MainThread Hello from main\n" "2512 Thread-1 Hi from myfunc\n" "3009 MainThread Hello from main\n" "3013 Thread-1 Hi from myfunc\n" "3515 Thread-1 Hi from myfunc\n" "3761 MainThread Hello from main\n" "4017 Thread-1 Hi from myfunc\n" "4513 MainThread Hello from main\n" "4518 Thread-1 Hi from myfunc" msgstr "" #: ../../howto/logging-cookbook.rst:155 msgid "" "This shows the logging output interspersed as one might expect. This " "approach works for more threads than shown here, of course." msgstr "" "予想した通りかもしれませんが、ログ出力が散らばっているのが分かります。\n" "もちろん、この手法はより多くのスレッドでも上手くいきます。" #: ../../howto/logging-cookbook.rst:159 msgid "Multiple handlers and formatters" msgstr "複数の handler と formatter" #: ../../howto/logging-cookbook.rst:161 msgid "" "Loggers are plain Python objects. The :meth:`~Logger.addHandler` method has " "no minimum or maximum quota for the number of handlers you may add. " "Sometimes it will be beneficial for an application to log all messages of " "all severities to a text file while simultaneously logging errors or above " "to the console. To set this up, simply configure the appropriate handlers. " "The logging calls in the application code will remain unchanged. Here is a " "slight modification to the previous simple module-based configuration " "example::" msgstr "" "logger は通常の Python オブジェクトです。 :meth:`~Logger.addHandler` メソッド" "は追加されるハンドラの個数について最小値も最大値も定めていません。時にアプリ" "ケーションがすべての深刻度のすべてのメッセージをテキストファイルに記録しつ" "つ、同時にエラーやそれ以上のものをコンソールに出力することが役に立ちます。こ" "れを実現する方法は、単に適切なハンドラを設定するだけです。アプリケーション" "コードの中のログ記録の呼び出しは変更されずに残ります。少し前に取り上げた単純" "なモジュール式の例を少し変えるとこうなります::" #: ../../howto/logging-cookbook.rst:169 msgid "" "import logging\n" "\n" "logger = logging.getLogger('simple_example')\n" "logger.setLevel(logging.DEBUG)\n" "# create file handler which logs even debug messages\n" "fh = logging.FileHandler('spam.log')\n" "fh.setLevel(logging.DEBUG)\n" "# create console handler with a higher log level\n" "ch = logging.StreamHandler()\n" "ch.setLevel(logging.ERROR)\n" "# create formatter and add it to the handlers\n" "formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " "%(message)s')\n" "ch.setFormatter(formatter)\n" "fh.setFormatter(formatter)\n" "# add the handlers to logger\n" "logger.addHandler(ch)\n" "logger.addHandler(fh)\n" "\n" "# 'application' code\n" "logger.debug('debug message')\n" "logger.info('info message')\n" "logger.warning('warn message')\n" "logger.error('error message')\n" "logger.critical('critical message')" msgstr "" #: ../../howto/logging-cookbook.rst:194 msgid "" "Notice that the 'application' code does not care about multiple handlers. " "All that changed was the addition and configuration of a new handler named " "*fh*." msgstr "" "'application' 部分のコードは複数の handler について何も気にしていないことに注" "目してください。変更した箇所は新しい *fh* という名の handler を追加して設定し" "たところがすべてです。" #: ../../howto/logging-cookbook.rst:197 msgid "" "The ability to create new handlers with higher- or lower-severity filters " "can be very helpful when writing and testing an application. Instead of " "using many ``print`` statements for debugging, use ``logger.debug``: Unlike " "the print statements, which you will have to delete or comment out later, " "the logger.debug statements can remain intact in the source code and remain " "dormant until you need them again. At that time, the only change that needs " "to happen is to modify the severity level of the logger and/or handler to " "debug." msgstr "" "新しい handler を、異なる深刻度に対する filter と共に生成できることは、アプリ" "ケーションを書いてテストを行うときとても助けになります。デバッグ用にたくさん" "の ``print`` 文を使う代わりに ``logger.debug`` を使いましょう。あとで消したり" "コメントアウトしたりしなければならない print 文と違って、logger.debug 命令は" "ソースコードの中にそのまま残しておいて再び必要になるまで休眠させておけます。" "その時必要になるのはただ logger および/または handler の深刻度の設定をいじる" "ことだけです。" #: ../../howto/logging-cookbook.rst:208 msgid "Logging to multiple destinations" msgstr "複数の出力先にログを出力する" #: ../../howto/logging-cookbook.rst:210 msgid "" "Let's say you want to log to console and file with different message formats " "and in differing circumstances. Say you want to log messages with levels of " "DEBUG and higher to file, and those messages at level INFO and higher to the " "console. Let's also assume that the file should contain timestamps, but the " "console messages should not. Here's how you can achieve this::" msgstr "" "コンソールとファイルに、別々のメッセージ書式で、別々の状況に応じたログ出力を" "行わせたいとしましょう。例えば DEBUG よりも高いレベルのメッセージはファイルに" "記録し、INFO 以上のレベルのメッセージはコンソールに出力したいという場合です。" "また、ファイルにはタイムスタンプを記録し、コンソールには出力しないとします。" "以下のようにすれば、こうした挙動を実現できます::" #: ../../howto/logging-cookbook.rst:216 msgid "" "import logging\n" "\n" "# set up logging to file - see previous section for more details\n" "logging.basicConfig(level=logging.DEBUG,\n" " format='%(asctime)s %(name)-12s %(levelname)-8s " "%(message)s',\n" " datefmt='%m-%d %H:%M',\n" " filename='/tmp/myapp.log',\n" " filemode='w')\n" "# define a Handler which writes INFO messages or higher to the sys.stderr\n" "console = logging.StreamHandler()\n" "console.setLevel(logging.INFO)\n" "# set a format which is simpler for console use\n" "formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n" "# tell the handler to use this format\n" "console.setFormatter(formatter)\n" "# add the handler to the root logger\n" "logging.getLogger('').addHandler(console)\n" "\n" "# Now, we can log to the root logger, or any other logger. First the " "root...\n" "logging.info('Jackdaws love my big sphinx of quartz.')\n" "\n" "# Now, define a couple of other loggers which might represent areas in your\n" "# application:\n" "\n" "logger1 = logging.getLogger('myapp.area1')\n" "logger2 = logging.getLogger('myapp.area2')\n" "\n" "logger1.debug('Quick zephyrs blow, vexing daft Jim.')\n" "logger1.info('How quickly daft jumping zebras vex.')\n" "logger2.warning('Jail zesty vixen who grabbed pay from quack.')\n" "logger2.error('The five boxing wizards jump quickly.')" msgstr "" #: ../../howto/logging-cookbook.rst:248 msgid "When you run this, on the console you will see" msgstr "これを実行すると、コンソールには以下のように出力されます:" #: ../../howto/logging-cookbook.rst:250 msgid "" "root : INFO Jackdaws love my big sphinx of quartz.\n" "myapp.area1 : INFO How quickly daft jumping zebras vex.\n" "myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.\n" "myapp.area2 : ERROR The five boxing wizards jump quickly." msgstr "" #: ../../howto/logging-cookbook.rst:257 msgid "and in the file you will see something like" msgstr "そして、ファイルには以下のように出力されるはずです:" #: ../../howto/logging-cookbook.rst:259 msgid "" "10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.\n" "10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.\n" "10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.\n" "10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from " "quack.\n" "10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly." msgstr "" #: ../../howto/logging-cookbook.rst:267 msgid "" "As you can see, the DEBUG message only shows up in the file. The other " "messages are sent to both destinations." msgstr "" "これを見て分かる通り、DEBUG メッセージはファイルだけに出力され、その他のメッ" "セージは両方に出力されます。" #: ../../howto/logging-cookbook.rst:270 msgid "" "This example uses console and file handlers, but you can use any number and " "combination of handlers you choose." msgstr "" "この例ではコンソールとファイルのハンドラだけを使っていますが、実際には任意の" "数のハンドラや組み合わせを使えます。" #: ../../howto/logging-cookbook.rst:273 msgid "" "Note that the above choice of log filename ``/tmp/myapp.log`` implies use of " "a standard location for temporary files on POSIX systems. On Windows, you " "may need to choose a different directory name for the log - just ensure that " "the directory exists and that you have the permissions to create and update " "files in it." msgstr "" "ここでファイル名として ``/tmp/myapp.log`` を選んだということは、一時ファイル" "の標準的な場所として POSIX システムを想定していることに注意してください。 " "Windows の場合、ディレクトリが存在し、そのディレクトリに対してファイルを更新" "するための適切な権限を有することを保証するために、ログファイル向けのディレク" "トリ名として異なる選択を取る必要があるでしょう。" #: ../../howto/logging-cookbook.rst:282 msgid "Custom handling of levels" msgstr "ログレベルのカスタム処理" #: ../../howto/logging-cookbook.rst:284 msgid "" "Sometimes, you might want to do something slightly different from the " "standard handling of levels in handlers, where all levels above a threshold " "get processed by a handler. To do this, you need to use filters. Let's look " "at a scenario where you want to arrange things as follows:" msgstr "" "しきい値以上のログレベル全てがハンドラによって処理される標準的な処理に対し" "て、ときにはわずかに異なる振る舞いを必要とすることもあるでしょう。そのような" "場合はフィルタを使う必要があります。以下のような処理が必要なシナリオについて" "取り上げてみましょう:" #: ../../howto/logging-cookbook.rst:289 msgid "Send messages of severity ``INFO`` and ``WARNING`` to ``sys.stdout``" msgstr "深刻度 ``INFO`` と ``WARNING`` のメッセージを ``sys.stdout`` に送る" #: ../../howto/logging-cookbook.rst:290 msgid "Send messages of severity ``ERROR`` and above to ``sys.stderr``" msgstr "深刻度 ``ERROR`` 以上のメッセージを ``sys.stderr`` に送る" #: ../../howto/logging-cookbook.rst:291 msgid "Send messages of severity ``DEBUG`` and above to file ``app.log``" msgstr "深刻度 ``DEBUG`` 以上のメッセージをファイル ``app.log`` に送る" #: ../../howto/logging-cookbook.rst:293 msgid "Suppose you configure logging with the following JSON:" msgstr "logging モジュールを下記の JSON によって構成したとしましょう:" #: ../../howto/logging-cookbook.rst:295 msgid "" "{\n" " \"version\": 1,\n" " \"disable_existing_loggers\": false,\n" " \"formatters\": {\n" " \"simple\": {\n" " \"format\": \"%(levelname)-8s - %(message)s\"\n" " }\n" " },\n" " \"handlers\": {\n" " \"stdout\": {\n" " \"class\": \"logging.StreamHandler\",\n" " \"level\": \"INFO\",\n" " \"formatter\": \"simple\",\n" " \"stream\": \"ext://sys.stdout\"\n" " },\n" " \"stderr\": {\n" " \"class\": \"logging.StreamHandler\",\n" " \"level\": \"ERROR\",\n" " \"formatter\": \"simple\",\n" " \"stream\": \"ext://sys.stderr\"\n" " },\n" " \"file\": {\n" " \"class\": \"logging.FileHandler\",\n" " \"formatter\": \"simple\",\n" " \"filename\": \"app.log\",\n" " \"mode\": \"w\"\n" " }\n" " },\n" " \"root\": {\n" " \"level\": \"DEBUG\",\n" " \"handlers\": [\n" " \"stderr\",\n" " \"stdout\",\n" " \"file\"\n" " ]\n" " }\n" "}" msgstr "" #: ../../howto/logging-cookbook.rst:335 msgid "" "This configuration does *almost* what we want, except that ``sys.stdout`` " "would show messages of severity ``ERROR`` and only events of this severity " "and higher will be tracked as well as ``INFO`` and ``WARNING`` messages. To " "prevent this, we can set up a filter which excludes those messages and add " "it to the relevant handler. This can be configured by adding a ``filters`` " "section parallel to ``formatters`` and ``handlers``:" msgstr "" #: ../../howto/logging-cookbook.rst:341 msgid "" "{\n" " \"filters\": {\n" " \"warnings_and_below\": {\n" " \"()\" : \"__main__.filter_maker\",\n" " \"level\": \"WARNING\"\n" " }\n" " }\n" "}" msgstr "" #: ../../howto/logging-cookbook.rst:352 msgid "and changing the section on the ``stdout`` handler to add it:" msgstr "" "そして ``stdout`` のハンドラに関するセクションにフィルターを追加します:" #: ../../howto/logging-cookbook.rst:354 msgid "" "{\n" " \"stdout\": {\n" " \"class\": \"logging.StreamHandler\",\n" " \"level\": \"INFO\",\n" " \"formatter\": \"simple\",\n" " \"stream\": \"ext://sys.stdout\",\n" " \"filters\": [\"warnings_and_below\"]\n" " }\n" "}" msgstr "" #: ../../howto/logging-cookbook.rst:366 msgid "" "A filter is just a function, so we can define the ``filter_maker`` (a " "factory function) as follows:" msgstr "" "フィルターは単なる関数なので、 ``filter_maker`` (ファクトリ関数) は以下のよう" "に定義することができます:" #: ../../howto/logging-cookbook.rst:369 msgid "" "def filter_maker(level):\n" " level = getattr(logging, level)\n" "\n" " def filter(record):\n" " return record.levelno <= level\n" "\n" " return filter" msgstr "" #: ../../howto/logging-cookbook.rst:379 msgid "" "This converts the string argument passed in to a numeric level, and returns " "a function which only returns ``True`` if the level of the passed in record " "is at or below the specified level. Note that in this example I have defined " "the ``filter_maker`` in a test script ``main.py`` that I run from the " "command line, so its module will be ``__main__`` - hence the ``__main__." "filter_maker`` in the filter configuration. You will need to change that if " "you define it in a different module." msgstr "" "この関数は引数として与えられた文字列をログレベルの数値に変換し、ログレコード" "内のログレベルが指定されたレベル以下の場合に ``True`` を返す関数を返します。" "この例では ``filter_maker`` をコマンドラインから実行するテストスクリプト " "``main.py`` で関数が定義されているため、フィルター設定上のモジュール名は " "``__main__`` になります。そのためフィルター設定の中では ``__main__." "filter_maker`` となります。異なるモジュールで関数を定義した場合、この部分を変" "更する必要があります。" #: ../../howto/logging-cookbook.rst:387 msgid "With the filter added, we can run ``main.py``, which in full is:" msgstr "" "フィルターを追加した ``main.py`` の全体像は以下のようになり、これで実行できる" "状態になりました:" #: ../../howto/logging-cookbook.rst:389 msgid "" "import json\n" "import logging\n" "import logging.config\n" "\n" "CONFIG = '''\n" "{\n" " \"version\": 1,\n" " \"disable_existing_loggers\": false,\n" " \"formatters\": {\n" " \"simple\": {\n" " \"format\": \"%(levelname)-8s - %(message)s\"\n" " }\n" " },\n" " \"filters\": {\n" " \"warnings_and_below\": {\n" " \"()\" : \"__main__.filter_maker\",\n" " \"level\": \"WARNING\"\n" " }\n" " },\n" " \"handlers\": {\n" " \"stdout\": {\n" " \"class\": \"logging.StreamHandler\",\n" " \"level\": \"INFO\",\n" " \"formatter\": \"simple\",\n" " \"stream\": \"ext://sys.stdout\",\n" " \"filters\": [\"warnings_and_below\"]\n" " },\n" " \"stderr\": {\n" " \"class\": \"logging.StreamHandler\",\n" " \"level\": \"ERROR\",\n" " \"formatter\": \"simple\",\n" " \"stream\": \"ext://sys.stderr\"\n" " },\n" " \"file\": {\n" " \"class\": \"logging.FileHandler\",\n" " \"formatter\": \"simple\",\n" " \"filename\": \"app.log\",\n" " \"mode\": \"w\"\n" " }\n" " },\n" " \"root\": {\n" " \"level\": \"DEBUG\",\n" " \"handlers\": [\n" " \"stderr\",\n" " \"stdout\",\n" " \"file\"\n" " ]\n" " }\n" "}\n" "'''\n" "\n" "def filter_maker(level):\n" " level = getattr(logging, level)\n" "\n" " def filter(record):\n" " return record.levelno <= level\n" "\n" " return filter\n" "\n" "logging.config.dictConfig(json.loads(CONFIG))\n" "logging.debug('A DEBUG message')\n" "logging.info('An INFO message')\n" "logging.warning('A WARNING message')\n" "logging.error('An ERROR message')\n" "logging.critical('A CRITICAL message')" msgstr "" #: ../../howto/logging-cookbook.rst:457 msgid "And after running it like this:" msgstr "これを以下のように実行します:" #: ../../howto/logging-cookbook.rst:459 msgid "python main.py 2>stderr.log >stdout.log" msgstr "" #: ../../howto/logging-cookbook.rst:463 msgid "We can see the results are as expected:" msgstr "すると期待通りの結果を得ることができます:" #: ../../howto/logging-cookbook.rst:465 msgid "" "$ more *.log\n" "::::::::::::::\n" "app.log\n" "::::::::::::::\n" "DEBUG - A DEBUG message\n" "INFO - An INFO message\n" "WARNING - A WARNING message\n" "ERROR - An ERROR message\n" "CRITICAL - A CRITICAL message\n" "::::::::::::::\n" "stderr.log\n" "::::::::::::::\n" "ERROR - An ERROR message\n" "CRITICAL - A CRITICAL message\n" "::::::::::::::\n" "stdout.log\n" "::::::::::::::\n" "INFO - An INFO message\n" "WARNING - A WARNING message" msgstr "" #: ../../howto/logging-cookbook.rst:489 msgid "Configuration server example" msgstr "設定サーバの例" #: ../../howto/logging-cookbook.rst:491 msgid "Here is an example of a module using the logging configuration server::" msgstr "ログ記録設定サーバを使うモジュールの例です::" #: ../../howto/logging-cookbook.rst:493 msgid "" "import logging\n" "import logging.config\n" "import time\n" "import os\n" "\n" "# read initial config file\n" "logging.config.fileConfig('logging.conf')\n" "\n" "# create and start listener on port 9999\n" "t = logging.config.listen(9999)\n" "t.start()\n" "\n" "logger = logging.getLogger('simpleExample')\n" "\n" "try:\n" " # loop through logging calls to see the difference\n" " # new configurations make, until Ctrl+C is pressed\n" " while True:\n" " logger.debug('debug message')\n" " logger.info('info message')\n" " logger.warning('warn message')\n" " logger.error('error message')\n" " logger.critical('critical message')\n" " time.sleep(5)\n" "except KeyboardInterrupt:\n" " # cleanup\n" " logging.config.stopListening()\n" " t.join()" msgstr "" #: ../../howto/logging-cookbook.rst:522 msgid "" "And here is a script that takes a filename and sends that file to the " "server, properly preceded with the binary-encoded length, as the new logging " "configuration::" msgstr "" "そしてファイル名を受け取ってそのファイルをサーバに送るスクリプトですが、それ" "に先だってバイナリエンコード長を新しいログ記録の設定として先に送っておきま" "す::" #: ../../howto/logging-cookbook.rst:526 msgid "" "#!/usr/bin/env python\n" "import socket, sys, struct\n" "\n" "with open(sys.argv[1], 'rb') as f:\n" " data_to_send = f.read()\n" "\n" "HOST = 'localhost'\n" "PORT = 9999\n" "s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" "print('connecting...')\n" "s.connect((HOST, PORT))\n" "print('sending config...')\n" "s.send(struct.pack('>L', len(data_to_send)))\n" "s.send(data_to_send)\n" "s.close()\n" "print('complete')" msgstr "" #: ../../howto/logging-cookbook.rst:547 msgid "Dealing with handlers that block" msgstr "ブロックする handler を扱う" #: ../../howto/logging-cookbook.rst:551 msgid "" "Sometimes you have to get your logging handlers to do their work without " "blocking the thread you're logging from. This is common in web applications, " "though of course it also occurs in other scenarios." msgstr "" "ときどき、logging を行っているスレッドをブロックせずに、handler が動くように" "しないといけないときがあります。これは Web アプリケーションではよくあることで" "すし、もちろん他のシナリオでも起きる話です。" #: ../../howto/logging-cookbook.rst:555 msgid "" "A common culprit which demonstrates sluggish behaviour is the :class:" "`SMTPHandler`: sending emails can take a long time, for a number of reasons " "outside the developer's control (for example, a poorly performing mail or " "network infrastructure). But almost any network-based handler can block: " "Even a :class:`SocketHandler` operation may do a DNS query under the hood " "which is too slow (and this query can be deep in the socket library code, " "below the Python layer, and outside your control)." msgstr "" "動作が鈍くなるときの元凶はたいてい、開発者のコントロール外にあるいくつもの理" "由で (例えば、残念なパフォーマンスのメールやネットワークのインフラ) 、 :" "class:`SMTPHandler`: が電子メールを送るのに時間がかかることです。しかし、ほと" "んどのネットワークをまたぐ handler はブロックする可能性があります: :class:" "`SocketHandler` による処理でさえ、裏で DNS への問い合わせというとても遅い処理" "を行うことがあります (そしてこの問い合わせ処理は、 Python の層より下のあなた" "の手の届かない、ソケットライブラリの深いところにある可能性もあります)。" #: ../../howto/logging-cookbook.rst:563 msgid "" "One solution is to use a two-part approach. For the first part, attach only " "a :class:`QueueHandler` to those loggers which are accessed from performance-" "critical threads. They simply write to their queue, which can be sized to a " "large enough capacity or initialized with no upper bound to their size. The " "write to the queue will typically be accepted quickly, though you will " "probably need to catch the :exc:`queue.Full` exception as a precaution in " "your code. If you are a library developer who has performance-critical " "threads in their code, be sure to document this (together with a suggestion " "to attach only ``QueueHandlers`` to your loggers) for the benefit of other " "developers who will use your code." msgstr "" "解決策の1つは、2パートに分離したアプローチを用いることです。最初のパートは、" "パフォーマンスが重要なスレッドからアクセスされる、 :class:`QueueHandler` だけ" "をアタッチした logger です。この logger は単に、十分大きい、あるいは無制限の" "容量を持ったキューに書き込むだけです。キューへの書き込みは通常すぐに完了しま" "すが、念の為に :exc:`queue.Full` 例外をキャッチする必要があるかもしれません。" "もしパフォーマンスクリティカルなスレッドを持つライブラリの開発者であるなら、" "このことを (``QueueHandler`` だけをアタッチした logger についての言及を添え" "て) ドキュメントに書いておきましょう。" #: ../../howto/logging-cookbook.rst:574 msgid "" "The second part of the solution is :class:`QueueListener`, which has been " "designed as the counterpart to :class:`QueueHandler`. A :class:" "`QueueListener` is very simple: it's passed a queue and some handlers, and " "it fires up an internal thread which listens to its queue for LogRecords " "sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that " "matter). The ``LogRecords`` are removed from the queue and passed to the " "handlers for processing." msgstr "" "2つ目のパートは :class:`QueueHandler` の対向として作られた :class:" "`QueueListener` です。 :class:`QueueListener` はとてもシンプルで、キューと " "handler を渡され、内部で ``QueueHandler`` (もしくは他の ``LogRecord`` の出力" "元) から送られた LogRecord をキューから受け取るスレッドを起動します。 " "``LogRecord`` をキューから取り出して、 handler に渡して処理させます。" #: ../../howto/logging-cookbook.rst:582 msgid "" "The advantage of having a separate :class:`QueueListener` class is that you " "can use the same instance to service multiple ``QueueHandlers``. This is " "more resource-friendly than, say, having threaded versions of the existing " "handler classes, which would eat up one thread per handler for no particular " "benefit." msgstr "" "分離した :class:`QueueListener` クラスを持つメリットは、複数の " "``QueueHandler`` に対して1つのインスタンスで logging できることです。既存の " "handler のスレッド利用版を使って handler ごとにスレッドを持つよりはずっとリ" "ソースにやさしくなります。" #: ../../howto/logging-cookbook.rst:587 msgid "An example of using these two classes follows (imports omitted)::" msgstr "この2つのクラスを利用する例です (import は省略)::" #: ../../howto/logging-cookbook.rst:589 msgid "" "que = queue.Queue(-1) # no limit on size\n" "queue_handler = QueueHandler(que)\n" "handler = logging.StreamHandler()\n" "listener = QueueListener(que, handler)\n" "root = logging.getLogger()\n" "root.addHandler(queue_handler)\n" "formatter = logging.Formatter('%(threadName)s: %(message)s')\n" "handler.setFormatter(formatter)\n" "listener.start()\n" "# The log output will display the thread which generated\n" "# the event (the main thread) rather than the internal\n" "# thread which monitors the internal queue. This is what\n" "# you want to happen.\n" "root.warning('Look out!')\n" "listener.stop()" msgstr "" #: ../../howto/logging-cookbook.rst:605 msgid "which, when run, will produce:" msgstr "実行すると次のように出力します:" #: ../../howto/logging-cookbook.rst:607 msgid "MainThread: Look out!" msgstr "" #: ../../howto/logging-cookbook.rst:611 msgid "" "Although the earlier discussion wasn't specifically talking about async " "code, but rather about slow logging handlers, it should be noted that when " "logging from async code, network and even file handlers could lead to " "problems (blocking the event loop) because some logging is done from :mod:" "`asyncio` internals. It might be best, if any async code is used in an " "application, to use the above approach for logging, so that any blocking " "code runs only in the ``QueueListener`` thread." msgstr "" "上述の議論は特に同期コードにについてのものではなく、むしろ遅いロギングハンド" "ラについてでしたが、非同期コードやネットワーク、あるいはファイルハンドラから" "のロギングでさえも (イベントループをブロックしてしまう) 問題につながる可能性" "があることには注意すべきでしょう。これはいくつかのロギングが :mod:`asyncio` " "内部で行われることが理由です。何らかの非同期コードがアプリケーションの中で使" "われている場合、ロギングには上記のアプローチを使っていかなるブロッキングコー" "ドも ``QueueListener`` スレッド内だけで実行されるようにしておくことが最も良い" "でしょう。" #: ../../howto/logging-cookbook.rst:619 msgid "" "Prior to Python 3.5, the :class:`QueueListener` always passed every message " "received from the queue to every handler it was initialized with. (This was " "because it was assumed that level filtering was all done on the other side, " "where the queue is filled.) From 3.5 onwards, this behaviour can be changed " "by passing a keyword argument ``respect_handler_level=True`` to the " "listener's constructor. When this is done, the listener compares the level " "of each message with the handler's level, and only passes a message to a " "handler if it's appropriate to do so." msgstr "" "Python 3.5 以前は、 :class:`QueueListener` クラスは常にキューから受け取った" "メッセージを、初期化元となっているそれぞれのハンドラーに受け渡していました。 " "( というのも、レベルフィルターリングは別サイド、つまり、キューが満たされてい" "る場所で処理されるということが想定されているからです) Python 3.5以降では、" "キーワードとなる引数 ``respect_handler_level=True`` をリスナーのコントラク" "ターに受け渡すことで、この挙動を変更することができるようになっています。これ" "が行われると、各メッセージのレベルをハンドラーのレベルと比較して、そうするこ" "とが適切な場合のみ、メッセージをハンドラーに渡します。" #: ../../howto/logging-cookbook.rst:629 msgid "" "The :class:`QueueListener` can be started (and stopped) via the :keyword:" "`with` statement. For example:" msgstr "" #: ../../howto/logging-cookbook.rst:633 msgid "" "with QueueListener(que, handler) as listener:\n" " # The queue listener automatically starts\n" " # when the 'with' block is entered.\n" " pass\n" "# The queue listener automatically stops once\n" "# the 'with' block is exited." msgstr "" #: ../../howto/logging-cookbook.rst:645 msgid "Sending and receiving logging events across a network" msgstr "ネットワーク越しの logging イベントの送受信" #: ../../howto/logging-cookbook.rst:647 msgid "" "Let's say you want to send logging events across a network, and handle them " "at the receiving end. A simple way of doing this is attaching a :class:" "`SocketHandler` instance to the root logger at the sending end::" msgstr "" "ログイベントをネットワーク越しに送信し、受信端でそれを処理したいとしましょ" "う。 :class:`SocketHandler` インスタンスを送信端の root logger にアタッチすれ" "ば、簡単に実現できます::" #: ../../howto/logging-cookbook.rst:651 msgid "" "import logging, logging.handlers\n" "\n" "rootLogger = logging.getLogger('')\n" "rootLogger.setLevel(logging.DEBUG)\n" "socketHandler = logging.handlers.SocketHandler('localhost',\n" " logging.handlers.DEFAULT_TCP_LOGGING_PORT)\n" "# don't bother with a formatter, since a socket handler sends the event as\n" "# an unformatted pickle\n" "rootLogger.addHandler(socketHandler)\n" "\n" "# Now, we can log to the root logger, or any other logger. First the " "root...\n" "logging.info('Jackdaws love my big sphinx of quartz.')\n" "\n" "# Now, define a couple of other loggers which might represent areas in your\n" "# application:\n" "\n" "logger1 = logging.getLogger('myapp.area1')\n" "logger2 = logging.getLogger('myapp.area2')\n" "\n" "logger1.debug('Quick zephyrs blow, vexing daft Jim.')\n" "logger1.info('How quickly daft jumping zebras vex.')\n" "logger2.warning('Jail zesty vixen who grabbed pay from quack.')\n" "logger2.error('The five boxing wizards jump quickly.')" msgstr "" #: ../../howto/logging-cookbook.rst:675 msgid "" "At the receiving end, you can set up a receiver using the :mod:" "`socketserver` module. Here is a basic working example::" msgstr "" "受信端では :mod:`socketserver` モジュールを使って受信プログラムを作成しておき" "ます。簡単な実用プログラムを以下に示します::" #: ../../howto/logging-cookbook.rst:678 msgid "" "import pickle\n" "import logging\n" "import logging.handlers\n" "import socketserver\n" "import struct\n" "\n" "\n" "class LogRecordStreamHandler(socketserver.StreamRequestHandler):\n" " \"\"\"Handler for a streaming logging request.\n" "\n" " This basically logs the record using whatever logging policy is\n" " configured locally.\n" " \"\"\"\n" "\n" " def handle(self):\n" " \"\"\"\n" " Handle multiple requests - each expected to be a 4-byte length,\n" " followed by the LogRecord in pickle format. Logs the record\n" " according to whatever policy is configured locally.\n" " \"\"\"\n" " while True:\n" " chunk = self.connection.recv(4)\n" " if len(chunk) < 4:\n" " break\n" " slen = struct.unpack('>L', chunk)[0]\n" " chunk = self.connection.recv(slen)\n" " while len(chunk) < slen:\n" " chunk = chunk + self.connection.recv(slen - len(chunk))\n" " obj = self.unPickle(chunk)\n" " record = logging.makeLogRecord(obj)\n" " self.handleLogRecord(record)\n" "\n" " def unPickle(self, data):\n" " return pickle.loads(data)\n" "\n" " def handleLogRecord(self, record):\n" " # if a name is specified, we use the named logger rather than the " "one\n" " # implied by the record.\n" " if self.server.logname is not None:\n" " name = self.server.logname\n" " else:\n" " name = record.name\n" " logger = logging.getLogger(name)\n" " # N.B. EVERY record gets logged. This is because Logger.handle\n" " # is normally called AFTER logger-level filtering. If you want\n" " # to do filtering, do it at the client end to save wasting\n" " # cycles and network bandwidth!\n" " logger.handle(record)\n" "\n" "class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):\n" " \"\"\"\n" " Simple TCP socket-based logging receiver suitable for testing.\n" " \"\"\"\n" "\n" " allow_reuse_address = True\n" "\n" " def __init__(self, host='localhost',\n" " port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,\n" " handler=LogRecordStreamHandler):\n" " socketserver.ThreadingTCPServer.__init__(self, (host, port), " "handler)\n" " self.abort = 0\n" " self.timeout = 1\n" " self.logname = None\n" "\n" " def serve_until_stopped(self):\n" " import select\n" " abort = 0\n" " while not abort:\n" " rd, wr, ex = select.select([self.socket.fileno()],\n" " [], [],\n" " self.timeout)\n" " if rd:\n" " self.handle_request()\n" " abort = self.abort\n" "\n" "def main():\n" " logging.basicConfig(\n" " format='%(relativeCreated)5d %(name)-15s %(levelname)-8s " "%(message)s')\n" " tcpserver = LogRecordSocketReceiver()\n" " print('About to start TCP server...')\n" " tcpserver.serve_until_stopped()\n" "\n" "if __name__ == '__main__':\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:763 msgid "" "First run the server, and then the client. On the client side, nothing is " "printed on the console; on the server side, you should see something like:" msgstr "" "先にサーバを起動しておき、次にクライアントを起動します。クライアント側では、" "コンソールには何も出力されません; サーバ側では以下のようなメッセージを目にす" "るはずです::" #: ../../howto/logging-cookbook.rst:766 msgid "" "About to start TCP server...\n" " 59 root INFO Jackdaws love my big sphinx of quartz.\n" " 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.\n" " 69 myapp.area1 INFO How quickly daft jumping zebras vex.\n" " 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.\n" " 69 myapp.area2 ERROR The five boxing wizards jump quickly." msgstr "" #: ../../howto/logging-cookbook.rst:775 msgid "" "Note that there are some security issues with pickle in some scenarios. If " "these affect you, you can use an alternative serialization scheme by " "overriding the :meth:`~SocketHandler.makePickle` method and implementing " "your alternative there, as well as adapting the above script to use your " "alternative serialization." msgstr "" "注意: pickle にはいくつかのシナリオでセキュリティ上の問題があります。これら" "が影響する場合は、 :meth:`~SocketHandler.makePickle` メソッドをオーバーライド" "し代替シリアライズ手法を実装して、それを使うように上記のスクリプトを修正する" "こともできます。" #: ../../howto/logging-cookbook.rst:783 msgid "Running a logging socket listener in production" msgstr "作成中のロギングソケットのリスナーを実行する" #: ../../howto/logging-cookbook.rst:787 msgid "" "To run a logging listener in production, you may need to use a process-" "management tool such as `Supervisor `_. `Here is a " "Gist `__ which provides the bare-bones files to run " "the above functionality using Supervisor. It consists of the following files:" msgstr "" "作成中のロギングリスナーを実行するためには、 `Supervisor `_ のようなプロセス管理ツールを使う必要があるかもしれません。 `こちらの " "Gist `__ は Supervisor を使って上記の機能を実行するた" "めの必要最低限のファイルを提供しています。以下のファイルが必要になります:" #: ../../howto/logging-cookbook.rst:794 msgid "File" msgstr "ファイル" #: ../../howto/logging-cookbook.rst:794 msgid "Purpose" msgstr "目的" #: ../../howto/logging-cookbook.rst:796 msgid ":file:`prepare.sh`" msgstr ":file:`prepare.sh`" #: ../../howto/logging-cookbook.rst:796 msgid "A Bash script to prepare the environment for testing" msgstr "試験用の環境を準備する Bash スクリプト" #: ../../howto/logging-cookbook.rst:799 msgid ":file:`supervisor.conf`" msgstr ":file:`supervisor.conf`" #: ../../howto/logging-cookbook.rst:799 msgid "" "The Supervisor configuration file, which has entries for the listener and a " "multi-process web application" msgstr "" "リスナーとマルチプロセスの web アプリケーションのための設定を含む Supervisor " "の設定ファイル" #: ../../howto/logging-cookbook.rst:803 msgid ":file:`ensure_app.sh`" msgstr ":file:`ensure_app.sh`" #: ../../howto/logging-cookbook.rst:803 msgid "" "A Bash script to ensure that Supervisor is running with the above " "configuration" msgstr "" "Supervisor が上記の設定で実行されていることを保証するための Bash スクリプト" #: ../../howto/logging-cookbook.rst:806 msgid ":file:`log_listener.py`" msgstr ":file:`log_listener.py`" #: ../../howto/logging-cookbook.rst:806 msgid "" "The socket listener program which receives log events and records them to a " "file" msgstr "ログイベントを受信してファイルに記録するソケットリスナープログラム" #: ../../howto/logging-cookbook.rst:809 msgid ":file:`main.py`" msgstr ":file:`main.py`" #: ../../howto/logging-cookbook.rst:809 msgid "" "A simple web application which performs logging via a socket connected to " "the listener" msgstr "" "リスナーに接続されたソケットを通じてロギングを実行する簡単な web アプリケー" "ション" #: ../../howto/logging-cookbook.rst:812 msgid ":file:`webapp.json`" msgstr ":file:`webapp.json`" #: ../../howto/logging-cookbook.rst:812 msgid "A JSON configuration file for the web application" msgstr "web アプリケーションのための JSON 設定ファイル" #: ../../howto/logging-cookbook.rst:814 msgid ":file:`client.py`" msgstr ":file:`client.py`" #: ../../howto/logging-cookbook.rst:814 msgid "A Python script to exercise the web application" msgstr "web アプリケーションを起動するための Python スクリプト" #: ../../howto/logging-cookbook.rst:817 msgid "" "The web application uses `Gunicorn `_, which is a " "popular web application server that starts multiple worker processes to " "handle requests. This example setup shows how the workers can write to the " "same log file without conflicting with one another --- they all go through " "the socket listener." msgstr "" "この web アプリケーションは、リクエストを処理する複数のワーカープロセスを起動" "する web アプリケーションサーバーである `Gunicorn `_ " "を使っています。ここに例として挙げた設定は、複数のワーカーがいかにして互いに" "衝突することなく同じログファイルに書き込みを行うことができるかを示しています " "--- ワーカーは全てソケットリスナーを通じてログを書き込むのです。" #: ../../howto/logging-cookbook.rst:822 msgid "To test these files, do the following in a POSIX environment:" msgstr "" "これらのファイルを試すためには、 POSIX 環境において以下を行なってください:" #: ../../howto/logging-cookbook.rst:824 msgid "" "Download `the Gist `__ as a ZIP archive using the :" "guilabel:`Download ZIP` button." msgstr "" ":guilabel:`Download ZIP` ボタンを押して `Gist `__ を " "ZIP アーカイブとしてダウンロードしてください。" #: ../../howto/logging-cookbook.rst:827 msgid "Unzip the above files from the archive into a scratch directory." msgstr "アーカイブファイルをスクラッチディレクトリに展開してください。" #: ../../howto/logging-cookbook.rst:829 msgid "" "In the scratch directory, run ``bash prepare.sh`` to get things ready. This " "creates a :file:`run` subdirectory to contain Supervisor-related and log " "files, and a :file:`venv` subdirectory to contain a virtual environment into " "which ``bottle``, ``gunicorn`` and ``supervisor`` are installed." msgstr "" "準備のために、スクラッチディレクトリにおいて ``bash prepare.sh`` を実行してく" "ださい。これにより Supervisor 関連のファイルおよびログファイルのための :file:" "`run` サブディレクトリ、および ``bottle``, ``gunicorn`` そして " "``supervisor`` がインストールされる仮想環境を含む :file:`venv` サブディレクト" "リが生成されます。" #: ../../howto/logging-cookbook.rst:834 msgid "" "Run ``bash ensure_app.sh`` to ensure that Supervisor is running with the " "above configuration." msgstr "" "``bash ensure_app.sh`` を実行して Supervisor が上記の設定で実行されていること" "を確認してください。" #: ../../howto/logging-cookbook.rst:837 msgid "" "Run ``venv/bin/python client.py`` to exercise the web application, which " "will lead to records being written to the log." msgstr "" "``venv/bin/python client.py`` を実行して web アプリケーションを起動してくださ" "い。これによりログにレコードが書き込まれるはずです。" #: ../../howto/logging-cookbook.rst:840 msgid "" "Inspect the log files in the :file:`run` subdirectory. You should see the " "most recent log lines in files matching the pattern :file:`app.log*`. They " "won't be in any particular order, since they have been handled concurrently " "by different worker processes in a non-deterministic way." msgstr "" ":file:`run` サブディレクトリにあるログファイルを調べてください。最新のログ" "は、パターン :file:`app.log*` に一致する名前のファイルにあるはずです。ログは" "異なるワーカープロセスによって非決定論的な形で並行に処理されるため、特定の決" "まった順番にはなりません。" #: ../../howto/logging-cookbook.rst:845 msgid "" "You can shut down the listener and the web application by running ``venv/bin/" "supervisorctl -c supervisor.conf shutdown``." msgstr "" "リスナーと web アプリケーションは ``venv/bin/supervisorctl -c supervisor." "conf shutdown`` を実行することでシャットダウンできます。" #: ../../howto/logging-cookbook.rst:848 msgid "" "You may need to tweak the configuration files in the unlikely event that the " "configured ports clash with something else in your test environment." msgstr "" "ありそうもないことですが、テスト環境で設定したポートが別の設定と衝突してし" "まった場合、設定ファイルを修正する必要があるかもしれません。" #: ../../howto/logging-cookbook.rst:851 msgid "" "The default configuration uses a TCP socket on port 9020. You can use a Unix " "Domain socket instead of a TCP socket by doing the following:" msgstr "" #: ../../howto/logging-cookbook.rst:854 msgid "" "In :file:`listener.json`, add a ``socket`` key with the path to the domain " "socket you want to use. If this key is present, the listener listens on the " "corresponding domain socket and not on a TCP socket (the ``port`` key is " "ignored)." msgstr "" #: ../../howto/logging-cookbook.rst:859 msgid "" "In :file:`webapp.json`, change the socket handler configuration dictionary " "so that the ``host`` value is the path to the domain socket, and set the " "``port`` value to ``null``." msgstr "" #: ../../howto/logging-cookbook.rst:869 msgid "Adding contextual information to your logging output" msgstr "コンテキスト情報をログ記録出力に付加する" #: ../../howto/logging-cookbook.rst:871 msgid "" "Sometimes you want logging output to contain contextual information in " "addition to the parameters passed to the logging call. For example, in a " "networked application, it may be desirable to log client-specific " "information in the log (e.g. remote client's username, or IP address). " "Although you could use the *extra* parameter to achieve this, it's not " "always convenient to pass the information in this way. While it might be " "tempting to create :class:`Logger` instances on a per-connection basis, this " "is not a good idea because these instances are not garbage collected. While " "this is not a problem in practice, when the number of :class:`Logger` " "instances is dependent on the level of granularity you want to use in " "logging an application, it could be hard to manage if the number of :class:" "`Logger` instances becomes effectively unbounded." msgstr "" "時にはログ記録出力にログ関数の呼び出し時に渡されたパラメータに加えてコンテキ" "スト情報を含めたいこともあるでしょう。たとえば、ネットワークアプリケーション" "で、クライアント固有の情報 (例: リモートクライアントの名前、 IP アドレス) も" "ログ記録に残しておきたいと思ったとしましょう。 *extra* パラメータをこの目的に" "使うこともできますが、いつでもこの方法で情報を渡すのが便利なやり方とも限りま" "せん。また接続ごとに :class:`Logger` インスタンスを生成する誘惑に駆られるかも" "しれませんが、生成した :class:`Logger` インスタンスはガーベジコレクションで回" "収されないので、これは良いアイデアとは言えません。この例は現実的な問題ではな" "いかもしれませんが、 :class:`Logger` インスタンスの個数がアプリケーションの中" "でログ記録が行われるレベルの粒度に依存する場合、 :class:`Logger` インスタンス" "の個数が事実上無制限にならないと、管理が難しくなります。" #: ../../howto/logging-cookbook.rst:886 msgid "Using LoggerAdapters to impart contextual information" msgstr "LoggerAdapter を使ったコンテキスト情報の伝達" #: ../../howto/logging-cookbook.rst:888 msgid "" "An easy way in which you can pass contextual information to be output along " "with logging event information is to use the :class:`LoggerAdapter` class. " "This class is designed to look like a :class:`Logger`, so that you can call :" "meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`, :meth:" "`exception`, :meth:`critical` and :meth:`log`. These methods have the same " "signatures as their counterparts in :class:`Logger`, so you can use the two " "types of instances interchangeably." msgstr "" "logging イベントの情報と一緒に出力されるコンテキスト情報を渡す簡単な方法" "は、 :class:`LoggerAdapter` を使うことです。このクラスは :class:`Logger` のよ" "うに見えるように設計されていて、 :meth:`debug`, :meth:`info`, :meth:" "`warning`, :meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log` の" "各メソッドを呼び出せるようになっています。これらのメソッドは対応する :class:" "`Logger` のメソッドと同じ引数を取るので、二つの型を取り替えて使うことができま" "す。" #: ../../howto/logging-cookbook.rst:896 msgid "" "When you create an instance of :class:`LoggerAdapter`, you pass it a :class:" "`Logger` instance and a dict-like object which contains your contextual " "information. When you call one of the logging methods on an instance of :" "class:`LoggerAdapter`, it delegates the call to the underlying instance of :" "class:`Logger` passed to its constructor, and arranges to pass the " "contextual information in the delegated call. Here's a snippet from the code " "of :class:`LoggerAdapter`::" msgstr "" ":class:`LoggerAdapter` のインスタンスを生成する際には、 :class:`Logger` イン" "スタンスとコンテキスト情報を収めた辞書風 (dict-like) のオブジェクトを渡しま" "す。 :class:`LoggerAdapter` のログ記録メソッドを呼び出すと、呼び出しをコンス" "トラクタに渡された配下の :class:`Logger` インスタンスに委譲し、その際コンテキ" "スト情報をその委譲された呼び出しに埋め込みます。 :class:`LoggerAdapter` の" "コードから少し抜き出してみます::" #: ../../howto/logging-cookbook.rst:904 msgid "" "def debug(self, msg, /, *args, **kwargs):\n" " \"\"\"\n" " Delegate a debug call to the underlying logger, after adding\n" " contextual information from this adapter instance.\n" " \"\"\"\n" " msg, kwargs = self.process(msg, kwargs)\n" " self.logger.debug(msg, *args, **kwargs)" msgstr "" #: ../../howto/logging-cookbook.rst:912 msgid "" "The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where " "the contextual information is added to the logging output. It's passed the " "message and keyword arguments of the logging call, and it passes back " "(potentially) modified versions of these to use in the call to the " "underlying logger. The default implementation of this method leaves the " "message alone, but inserts an 'extra' key in the keyword argument whose " "value is the dict-like object passed to the constructor. Of course, if you " "had passed an 'extra' keyword argument in the call to the adapter, it will " "be silently overwritten." msgstr "" ":class:`LoggerAdapter` の :meth:`~LoggerAdapter.process` メソッドがコンテキス" "ト情報をログ出力に加える場所です。そこではログ記録呼び出しのメッセージとキー" "ワード引数が渡され、加工された (可能性のある) それらの情報を配下のロガーへの" "呼び出しに渡し直します。このメソッドのデフォルト実装ではメッセージは元のまま" "ですが、キーワード引数にはコンストラクタに渡された辞書風オブジェクトを値とし" "て \"extra\" キーが挿入されます。もちろん、呼び出し時に \"extra\" キーワード" "を使った場合には何事もなかったかのように上書きされます。" #: ../../howto/logging-cookbook.rst:921 msgid "" "The advantage of using 'extra' is that the values in the dict-like object " "are merged into the :class:`LogRecord` instance's __dict__, allowing you to " "use customized strings with your :class:`Formatter` instances which know " "about the keys of the dict-like object. If you need a different method, e.g. " "if you want to prepend or append the contextual information to the message " "string, you just need to subclass :class:`LoggerAdapter` and override :meth:" "`~LoggerAdapter.process` to do what you need. Here is a simple example::" msgstr "" "\"extra\" を用いる利点は辞書風オブジェクトの中の値が :class:`LogRecord` イン" "スタンスの __dict__ にマージされることで、辞書風オブジェクトのキーを知ってい" "る :class:`Formatter` を用意して文字列をカスタマイズするようにできることで" "す。それ以外のメソッドが必要なとき、たとえばコンテキスト情報をメッセージの前" "や後ろにつなげたい場合には、 :class:`LoggerAdapter` から :meth:" "`~LoggerAdapter.process` を望むようにオーバライドしたサブクラスを作ることが必" "要なだけです。次に挙げるのはこのクラスを使った例で、コンストラクタで使われる" "「辞書風」オブジェクトにどの振る舞いが必要なのかも示しています::" #: ../../howto/logging-cookbook.rst:929 msgid "" "class CustomAdapter(logging.LoggerAdapter):\n" " \"\"\"\n" " This example adapter expects the passed in dict-like object to have a\n" " 'connid' key, whose value in brackets is prepended to the log message.\n" " \"\"\"\n" " def process(self, msg, kwargs):\n" " return '[%s] %s' % (self.extra['connid'], msg), kwargs" msgstr "" #: ../../howto/logging-cookbook.rst:937 msgid "which you can use like this::" msgstr "これを次のように使うことができます::" #: ../../howto/logging-cookbook.rst:939 msgid "" "logger = logging.getLogger(__name__)\n" "adapter = CustomAdapter(logger, {'connid': some_conn_id})" msgstr "" #: ../../howto/logging-cookbook.rst:942 msgid "" "Then any events that you log to the adapter will have the value of " "``some_conn_id`` prepended to the log messages." msgstr "" "これで、この adapter 経由でログした全てのイベントに対して、``some_conn_id`` " "の値がログメッセージの前に追加されます。" #: ../../howto/logging-cookbook.rst:946 msgid "Using objects other than dicts to pass contextual information" msgstr "コンテキスト情報を渡すために dict 以外のオブジェクトを使う" #: ../../howto/logging-cookbook.rst:948 msgid "" "You don't need to pass an actual dict to a :class:`LoggerAdapter` - you " "could pass an instance of a class which implements ``__getitem__`` and " "``__iter__`` so that it looks like a dict to logging. This would be useful " "if you want to generate values dynamically (whereas the values in a dict " "would be constant)." msgstr "" ":class:`LoggerAdapter` に渡すのは本物の dict でなくても構いません。 " "``__getitem__`` と ``__iter__`` を実装していて logging が辞書のように扱えるク" "ラスのインスタンスを利用することができます。これは (dict の値が固定されるのに" "対して) 値を動的に生成できるので便利です。" #: ../../howto/logging-cookbook.rst:957 msgid "Using Filters to impart contextual information" msgstr "Filter を使ったコンテキスト情報の伝達" #: ../../howto/logging-cookbook.rst:959 msgid "" "You can also add contextual information to log output using a user-defined :" "class:`Filter`. ``Filter`` instances are allowed to modify the " "``LogRecords`` passed to them, including adding additional attributes which " "can then be output using a suitable format string, or if needed a custom :" "class:`Formatter`." msgstr "" "ユーザ定義の :class:`Filter` を使ってログ出力にコンテキスト情報を加えることも" "できます。 ``Filter`` インスタンスは、渡された ``LogRecords`` を修正すること" "ができます。これにより、適切なフォーマット文字列や必要なら :class:" "`Formatter` を使って、出力となる属性を新しく追加することも出来ます。" #: ../../howto/logging-cookbook.rst:964 msgid "" "For example in a web application, the request being processed (or at least, " "the interesting parts of it) can be stored in a threadlocal (:class:" "`threading.local`) variable, and then accessed from a ``Filter`` to add, " "say, information from the request - say, the remote IP address and remote " "user's username - to the ``LogRecord``, using the attribute names 'ip' and " "'user' as in the ``LoggerAdapter`` example above. In that case, the same " "format string can be used to get similar output to that shown above. Here's " "an example script::" msgstr "" "例えば、web アプリケーションで、処理されるリクエスト (または、少なくともその" "重要な部分) は、スレッドローカル (:class:`threading.local`) な変数に保存し" "て、 ``Filter`` からアクセスすることで、 ``LogRecord`` にリクエストの情報を追" "加できます。例えば、リモート IP アドレスやリモートユーザのユーザ名にアクセス" "したいなら、上述の ``LoggerAdapter`` の例のように属性名 'ip' や 'user' を使う" "といったようにです。その場合、同じフォーマット文字列を使って以下に示すように" "似たような出力を得られます。これはスクリプトの例です::" #: ../../howto/logging-cookbook.rst:973 msgid "" "import logging\n" "from random import choice\n" "\n" "class ContextFilter(logging.Filter):\n" " \"\"\"\n" " This is a filter which injects contextual information into the log.\n" "\n" " Rather than use actual contextual information, we just use random\n" " data in this demo.\n" " \"\"\"\n" "\n" " USERS = ['jim', 'fred', 'sheila']\n" " IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']\n" "\n" " def filter(self, record):\n" "\n" " record.ip = choice(ContextFilter.IPS)\n" " record.user = choice(ContextFilter.USERS)\n" " return True\n" "\n" "if __name__ == '__main__':\n" " levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, " "logging.CRITICAL)\n" " logging.basicConfig(level=logging.DEBUG,\n" " format='%(asctime)-15s %(name)-5s %(levelname)-8s " "IP: %(ip)-15s User: %(user)-8s %(message)s')\n" " a1 = logging.getLogger('a.b.c')\n" " a2 = logging.getLogger('d.e.f')\n" "\n" " f = ContextFilter()\n" " a1.addFilter(f)\n" " a2.addFilter(f)\n" " a1.debug('A debug message')\n" " a1.info('An info message with %s', 'some parameters')\n" " for x in range(10):\n" " lvl = choice(levels)\n" " lvlname = logging.getLevelName(lvl)\n" " a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, " "'parameters')" msgstr "" #: ../../howto/logging-cookbook.rst:1010 msgid "which, when run, produces something like:" msgstr "実行すると、以下のようになります:" #: ../../howto/logging-cookbook.rst:1012 msgid "" "2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A " "debug message\n" "2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An " "info message with some parameters\n" "2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A " "message at CRITICAL level with 2 parameters\n" "2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A " "message at ERROR level with 2 parameters\n" "2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A " "message at DEBUG level with 2 parameters\n" "2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A " "message at ERROR level with 2 parameters\n" "2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A " "message at CRITICAL level with 2 parameters\n" "2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A " "message at CRITICAL level with 2 parameters\n" "2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A " "message at DEBUG level with 2 parameters\n" "2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A " "message at ERROR level with 2 parameters\n" "2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A " "message at DEBUG level with 2 parameters\n" "2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A " "message at INFO level with 2 parameters" msgstr "" #: ../../howto/logging-cookbook.rst:1028 msgid "Use of ``contextvars``" msgstr "``contextvars`` の利用" #: ../../howto/logging-cookbook.rst:1030 msgid "" "Since Python 3.7, the :mod:`contextvars` module has provided context-local " "storage which works for both :mod:`threading` and :mod:`asyncio` processing " "needs. This type of storage may thus be generally preferable to thread-" "locals. The following example shows how, in a multi-threaded environment, " "logs can populated with contextual information such as, for example, request " "attributes handled by web applications." msgstr "" "Python 3.7 以降、 :mod:`contextvars` モジュールは :mod:`threading` と :mod:" "`asyncio` の両方の処理上のニーズを満たすコンテキストローカルな変数を提供して" "います。このタイプの変数はスレッドローカルな変数に適しています。以下の例は、" "マルチスレッド環境において、 いかにして web アプリケーションによって処理され" "るリクエスト属性のような処理の文脈上の情報とともにログを投入できるかを示しま" "す。" #: ../../howto/logging-cookbook.rst:1036 msgid "" "For the purposes of illustration, say that you have different web " "applications, each independent of the other but running in the same Python " "process and using a library common to them. How can each of these " "applications have their own log, where all logging messages from the library " "(and other request processing code) are directed to the appropriate " "application's log file, while including in the log additional contextual " "information such as client IP, HTTP request method and client username?" msgstr "" "説明のため、同じ Python プロセス上で共通のライブラリを使っている独立した複数" "の web アプリケーションがあるとします。これらのアプリケーションが、クライアン" "トの IP アドレスや HTTP リクエストメソッド、およびクライアントのユーザー名の" "ようなコンテキスト依存の情報を追加情報として含んだ自身のログを、共通のライブ" "ラリ (と他のリクエスト処理のためのコード) から各アプリケーションのログファイ" "ルへ適切に振り向けるためにはどのようにしたら良いでしょうか?" #: ../../howto/logging-cookbook.rst:1043 msgid "Let's assume that the library can be simulated by the following code:" msgstr "ここで、ライブラリは以下のコードで模することができるとします:" #: ../../howto/logging-cookbook.rst:1045 msgid "" "# webapplib.py\n" "import logging\n" "import time\n" "\n" "logger = logging.getLogger(__name__)\n" "\n" "def useful():\n" " # Just a representative event logged from the library\n" " logger.debug('Hello from webapplib!')\n" " # Just sleep for a bit so other threads get to run\n" " time.sleep(0.01)" msgstr "" #: ../../howto/logging-cookbook.rst:1059 msgid "" "We can simulate the multiple web applications by means of two simple " "classes, ``Request`` and ``WebApp``. These simulate how real threaded web " "applications work - each request is handled by a thread:" msgstr "" "複数の web アプリケーションは2つの簡単なクラス, ``Request`` と ``WebApp``, に" "よって模倣することができます。これらは実際のスレッド化された web アプリケー" "ションがどのように動作するかを模擬的にあらわしています - すなわち各リクエスト" "はスレッドで処理される状況です:" #: ../../howto/logging-cookbook.rst:1063 msgid "" "# main.py\n" "import argparse\n" "from contextvars import ContextVar\n" "import logging\n" "import os\n" "from random import choice\n" "import threading\n" "import webapplib\n" "\n" "logger = logging.getLogger(__name__)\n" "root = logging.getLogger()\n" "root.setLevel(logging.DEBUG)\n" "\n" "class Request:\n" " \"\"\"\n" " A simple dummy request class which just holds dummy HTTP request " "method,\n" " client IP address and client username\n" " \"\"\"\n" " def __init__(self, method, ip, user):\n" " self.method = method\n" " self.ip = ip\n" " self.user = user\n" "\n" "# A dummy set of requests which will be used in the simulation - we'll just " "pick\n" "# from this list randomly. Note that all GET requests are from 192.168.2." "XXX\n" "# addresses, whereas POST requests are from 192.16.3.XXX addresses. Three " "users\n" "# are represented in the sample requests.\n" "\n" "REQUESTS = [\n" " Request('GET', '192.168.2.20', 'jim'),\n" " Request('POST', '192.168.3.20', 'fred'),\n" " Request('GET', '192.168.2.21', 'sheila'),\n" " Request('POST', '192.168.3.21', 'jim'),\n" " Request('GET', '192.168.2.22', 'fred'),\n" " Request('POST', '192.168.3.22', 'sheila'),\n" "]\n" "\n" "# Note that the format string includes references to request context " "information\n" "# such as HTTP method, client IP and username\n" "\n" "formatter = logging.Formatter('%(threadName)-11s %(appName)s %(name)-9s " "%(user)-6s %(ip)s %(method)-4s %(message)s')\n" "\n" "# Create our context variables. These will be filled at the start of " "request\n" "# processing, and used in the logging that happens during that processing\n" "\n" "ctx_request = ContextVar('request')\n" "ctx_appname = ContextVar('appname')\n" "\n" "class InjectingFilter(logging.Filter):\n" " \"\"\"\n" " A filter which injects context-specific information into logs and " "ensures\n" " that only information for a specific webapp is included in its log\n" " \"\"\"\n" " def __init__(self, app):\n" " self.app = app\n" "\n" " def filter(self, record):\n" " request = ctx_request.get()\n" " record.method = request.method\n" " record.ip = request.ip\n" " record.user = request.user\n" " record.appName = appName = ctx_appname.get()\n" " return appName == self.app.name\n" "\n" "class WebApp:\n" " \"\"\"\n" " A dummy web application class which has its own handler and filter for " "a\n" " webapp-specific log.\n" " \"\"\"\n" " def __init__(self, name):\n" " self.name = name\n" " handler = logging.FileHandler(name + '.log', 'w')\n" " f = InjectingFilter(self)\n" " handler.setFormatter(formatter)\n" " handler.addFilter(f)\n" " root.addHandler(handler)\n" " self.num_requests = 0\n" "\n" " def process_request(self, request):\n" " \"\"\"\n" " This is the dummy method for processing a request. It's called on a\n" " different thread for every request. We store the context information " "into\n" " the context vars before doing anything else.\n" " \"\"\"\n" " ctx_request.set(request)\n" " ctx_appname.set(self.name)\n" " self.num_requests += 1\n" " logger.debug('Request processing started')\n" " webapplib.useful()\n" " logger.debug('Request processing finished')\n" "\n" "def main():\n" " fn = os.path.splitext(os.path.basename(__file__))[0]\n" " adhf = argparse.ArgumentDefaultsHelpFormatter\n" " ap = argparse.ArgumentParser(formatter_class=adhf, prog=fn,\n" " description='Simulate a couple of web '\n" " 'applications handling some '\n" " 'requests, showing how request " "'\n" " 'context can be used to '\n" " 'populate logs')\n" " aa = ap.add_argument\n" " aa('--count', '-c', type=int, default=100, help='How many requests to " "simulate')\n" " options = ap.parse_args()\n" "\n" " # Create the dummy webapps and put them in a list which we can use to " "select\n" " # from randomly\n" " app1 = WebApp('app1')\n" " app2 = WebApp('app2')\n" " apps = [app1, app2]\n" " threads = []\n" " # Add a common handler which will capture all events\n" " handler = logging.FileHandler('app.log', 'w')\n" " handler.setFormatter(formatter)\n" " root.addHandler(handler)\n" "\n" " # Generate calls to process requests\n" " for i in range(options.count):\n" " try:\n" " # Pick an app at random and a request for it to process\n" " app = choice(apps)\n" " request = choice(REQUESTS)\n" " # Process the request in its own thread\n" " t = threading.Thread(target=app.process_request, " "args=(request,))\n" " threads.append(t)\n" " t.start()\n" " except KeyboardInterrupt:\n" " break\n" "\n" " # Wait for the threads to terminate\n" " for t in threads:\n" " t.join()\n" "\n" " for app in apps:\n" " print('%s processed %s requests' % (app.name, app.num_requests))\n" "\n" "if __name__ == '__main__':\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:1203 msgid "" "If you run the above, you should find that roughly half the requests go " "into :file:`app1.log` and the rest into :file:`app2.log`, and the all the " "requests are logged to :file:`app.log`. Each webapp-specific log will " "contain only log entries for only that webapp, and the request information " "will be displayed consistently in the log (i.e. the information in each " "dummy request will always appear together in a log line). This is " "illustrated by the following shell output:" msgstr "" "上記のコードを実行すると、およそ半分のリクエストが :file:`app1.log` に、残り" "半分が :file:`app2.log` にそれぞれ記録され、同時に全てのリクエストが :file:" "`app.log` に記録されることがわかるでしょう。それぞれの web アプリケーション固" "有のログはそれぞれのアプリケーションからのログエントリだけを含み、リクエスト" "情報が矛盾なくログに表示されている (すなわち、各ダミーリクエストの情報は常に" "ログの行とともに現れる) はずです。このことは以下のシェルコマンドの出力により" "例示されています:" #: ../../howto/logging-cookbook.rst:1210 msgid "" "~/logging-contextual-webapp$ python main.py\n" "app1 processed 51 requests\n" "app2 processed 49 requests\n" "~/logging-contextual-webapp$ wc -l *.log\n" " 153 app1.log\n" " 147 app2.log\n" " 300 app.log\n" " 600 total\n" "~/logging-contextual-webapp$ head -3 app1.log\n" "Thread-3 (process_request) app1 __main__ jim 192.168.3.21 POST Request " "processing started\n" "Thread-3 (process_request) app1 webapplib jim 192.168.3.21 POST Hello " "from webapplib!\n" "Thread-5 (process_request) app1 __main__ jim 192.168.3.21 POST Request " "processing started\n" "~/logging-contextual-webapp$ head -3 app2.log\n" "Thread-1 (process_request) app2 __main__ sheila 192.168.2.21 GET Request " "processing started\n" "Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET Hello " "from webapplib!\n" "Thread-2 (process_request) app2 __main__ jim 192.168.2.20 GET Request " "processing started\n" "~/logging-contextual-webapp$ head app.log\n" "Thread-1 (process_request) app2 __main__ sheila 192.168.2.21 GET Request " "processing started\n" "Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET Hello " "from webapplib!\n" "Thread-2 (process_request) app2 __main__ jim 192.168.2.20 GET Request " "processing started\n" "Thread-3 (process_request) app1 __main__ jim 192.168.3.21 POST Request " "processing started\n" "Thread-2 (process_request) app2 webapplib jim 192.168.2.20 GET Hello " "from webapplib!\n" "Thread-3 (process_request) app1 webapplib jim 192.168.3.21 POST Hello " "from webapplib!\n" "Thread-4 (process_request) app2 __main__ fred 192.168.2.22 GET Request " "processing started\n" "Thread-5 (process_request) app1 __main__ jim 192.168.3.21 POST Request " "processing started\n" "Thread-4 (process_request) app2 webapplib fred 192.168.2.22 GET Hello " "from webapplib!\n" "Thread-6 (process_request) app1 __main__ jim 192.168.3.21 POST Request " "processing started\n" "~/logging-contextual-webapp$ grep app1 app1.log | wc -l\n" "153\n" "~/logging-contextual-webapp$ grep app2 app2.log | wc -l\n" "147\n" "~/logging-contextual-webapp$ grep app1 app.log | wc -l\n" "153\n" "~/logging-contextual-webapp$ grep app2 app.log | wc -l\n" "147" msgstr "" #: ../../howto/logging-cookbook.rst:1250 msgid "Imparting contextual information in handlers" msgstr "ハンドラ内でのコンテキスト情報の付与" #: ../../howto/logging-cookbook.rst:1252 msgid "" "Each :class:`~Handler` has its own chain of filters. If you want to add " "contextual information to a :class:`LogRecord` without leaking it to other " "handlers, you can use a filter that returns a new :class:`~LogRecord` " "instead of modifying it in-place, as shown in the following script::" msgstr "" ":class:`~Handler` はそれぞれ一連のフィルタを独自に持っています。コンテキスト" "情報を、他のハンドラに漏らすことなく :class:`LogRecord` に付加したい場合、以" "下に示すスクリプトのように、直接レコードを編集する代わりに新しい :class:" "`~LogRecord` を返すフィルタを使うことができます::" #: ../../howto/logging-cookbook.rst:1257 msgid "" "import copy\n" "import logging\n" "\n" "def filter(record: logging.LogRecord):\n" " record = copy.copy(record)\n" " record.user = 'jim'\n" " return record\n" "\n" "if __name__ == '__main__':\n" " logger = logging.getLogger()\n" " logger.setLevel(logging.INFO)\n" " handler = logging.StreamHandler()\n" " formatter = logging.Formatter('%(message)s from %(user)-8s')\n" " handler.setFormatter(formatter)\n" " handler.addFilter(filter)\n" " logger.addHandler(handler)\n" "\n" " logger.info('A log message')" msgstr "" #: ../../howto/logging-cookbook.rst:1279 msgid "Logging to a single file from multiple processes" msgstr "複数のプロセスからの単一ファイルへのログ記録" #: ../../howto/logging-cookbook.rst:1281 msgid "" "Although logging is thread-safe, and logging to a single file from multiple " "threads in a single process *is* supported, logging to a single file from " "*multiple processes* is *not* supported, because there is no standard way to " "serialize access to a single file across multiple processes in Python. If " "you need to log to a single file from multiple processes, one way of doing " "this is to have all the processes log to a :class:`~handlers.SocketHandler`, " "and have a separate process which implements a socket server which reads " "from the socket and logs to file. (If you prefer, you can dedicate one " "thread in one of the existing processes to perform this function.) :ref:" "`This section ` documents this approach in more detail and " "includes a working socket receiver which can be used as a starting point for " "you to adapt in your own applications." msgstr "" "ログ記録はスレッドセーフであり、単一プロセスの複数のスレッドからの単一ファイ" "ルへのログ記録はサポート *されています* が、 *複数プロセス* からの単一ファイ" "ルへのログ記録はサポート *されません* 。なぜなら、複数のプロセスをまたいで単" "一のファイルへのアクセスを直列化する標準の方法が Python には存在しないからで" "す。複数のプロセスから単一ファイルへログ記録しなければならないなら、最も良い" "方法は、すべてのプロセスが :class:`~handlers.SocketHandler` に対してログ記録" "を行い、独立したプロセスとしてソケットサーバを動かすことです。ソケットサーバ" "はソケットから読み取ってファイルにログを書き出します。 (この機能を実行するた" "めに、既存のプロセスの 1 つのスレッドを割り当てることもできます) :ref:`この" "節 ` では、このアプローチをさらに詳細に文書化しています。動" "作するソケット受信プログラムが含まれているので、アプリケーションに組み込むた" "めの出発点として使用できるでしょう。" #: ../../howto/logging-cookbook.rst:1294 msgid "" "You could also write your own handler which uses the :class:" "`~multiprocessing.Lock` class from the :mod:`multiprocessing` module to " "serialize access to the file from your processes. The stdlib :class:" "`FileHandler` and subclasses do not make use of :mod:`multiprocessing`." msgstr "" #: ../../howto/logging-cookbook.rst:1301 msgid "" "Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send " "all logging events to one of the processes in your multi-process " "application. The following example script demonstrates how you can do this; " "in the example a separate listener process listens for events sent by other " "processes and logs them according to its own logging configuration. Although " "the example only demonstrates one way of doing it (for example, you may want " "to use a listener thread rather than a separate listener process -- the " "implementation would be analogous) it does allow for completely different " "logging configurations for the listener and the other processes in your " "application, and can be used as the basis for code meeting your own specific " "requirements::" msgstr "" "別の方法として、 ``Queue`` と :class:`QueueHandler` を使って、マルチプロセス" "アプリケーションの1つのプロセスに全ての logging イベントを送る事ができます。" "次の例はこれを行う方法を示します。この例では独立した listener プロセスが他の" "プロセスから送られた event を受け取り、それを独自の logging 設定にしたがって" "保存します。この例は実装の方法の1つを示しているだけ (例えば、 listener プロセ" "スを分離する代わりに listener スレッドを使うこともできます) ですが、これは " "listener とアプリケーション内の他のプロセスで完全に異なる設定を使う例になって" "いるので、各自の要求に応じたコードを書く叩き台になるでしょう::" #: ../../howto/logging-cookbook.rst:1312 msgid "" "# You'll need these imports in your own code\n" "import logging\n" "import logging.handlers\n" "import multiprocessing\n" "\n" "# Next two import lines for this demo only\n" "from random import choice, random\n" "import time\n" "\n" "#\n" "# Because you'll want to define the logging configurations for listener and " "workers, the\n" "# listener and worker process functions take a configurer parameter which is " "a callable\n" "# for configuring logging for that process. These functions are also passed " "the queue,\n" "# which they use for communication.\n" "#\n" "# In practice, you can configure the listener however you want, but note " "that in this\n" "# simple example, the listener does not apply level or filter logic to " "received records.\n" "# In practice, you would probably want to do this logic in the worker " "processes, to avoid\n" "# sending events which would be filtered out between processes.\n" "#\n" "# The size of the rotated files is made small so you can see the results " "easily.\n" "def listener_configurer():\n" " root = logging.getLogger()\n" " h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)\n" " f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s " "%(levelname)-8s %(message)s')\n" " h.setFormatter(f)\n" " root.addHandler(h)\n" "\n" "# This is the listener process top-level loop: wait for logging events\n" "# (LogRecords)on the queue and handle them, quit when you get a None for a\n" "# LogRecord.\n" "def listener_process(queue, configurer):\n" " configurer()\n" " while True:\n" " try:\n" " record = queue.get()\n" " if record is None: # We send this as a sentinel to tell the " "listener to quit.\n" " break\n" " logger = logging.getLogger(record.name)\n" " logger.handle(record) # No level or filter logic applied - just " "do it!\n" " except Exception:\n" " import sys, traceback\n" " print('Whoops! Problem:', file=sys.stderr)\n" " traceback.print_exc(file=sys.stderr)\n" "\n" "# Arrays used for random selections in this demo\n" "\n" "LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,\n" " logging.ERROR, logging.CRITICAL]\n" "\n" "LOGGERS = ['a.b.c', 'd.e.f']\n" "\n" "MESSAGES = [\n" " 'Random message #1',\n" " 'Random message #2',\n" " 'Random message #3',\n" "]\n" "\n" "# The worker configuration is done at the start of the worker process run.\n" "# Note that on Windows you can't rely on fork semantics, so each process\n" "# will run the logging configuration code when it starts.\n" "def worker_configurer(queue):\n" " h = logging.handlers.QueueHandler(queue) # Just the one handler needed\n" " root = logging.getLogger()\n" " root.addHandler(h)\n" " # send all messages, for demo; no other level or filter logic applied.\n" " root.setLevel(logging.DEBUG)\n" "\n" "# This is the worker process top-level loop, which just logs ten events " "with\n" "# random intervening delays before terminating.\n" "# The print messages are just so you know it's doing something!\n" "def worker_process(queue, configurer):\n" " configurer(queue)\n" " name = multiprocessing.current_process().name\n" " print('Worker started: %s' % name)\n" " for i in range(10):\n" " time.sleep(random())\n" " logger = logging.getLogger(choice(LOGGERS))\n" " level = choice(LEVELS)\n" " message = choice(MESSAGES)\n" " logger.log(level, message)\n" " print('Worker finished: %s' % name)\n" "\n" "# Here's where the demo gets orchestrated. Create the queue, create and " "start\n" "# the listener, create ten workers and start them, wait for them to finish,\n" "# then send a None to the queue to tell the listener to finish.\n" "def main():\n" " queue = multiprocessing.Queue(-1)\n" " listener = multiprocessing.Process(target=listener_process,\n" " args=(queue, listener_configurer))\n" " listener.start()\n" " workers = []\n" " for i in range(10):\n" " worker = multiprocessing.Process(target=worker_process,\n" " args=(queue, worker_configurer))\n" " workers.append(worker)\n" " worker.start()\n" " for w in workers:\n" " w.join()\n" " queue.put_nowait(None)\n" " listener.join()\n" "\n" "if __name__ == '__main__':\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:1417 msgid "" "A variant of the above script keeps the logging in the main process, in a " "separate thread::" msgstr "上のスクリプトの亜種で、logging をメインプロセスの別スレッドで行う例::" #: ../../howto/logging-cookbook.rst:1420 msgid "" "import logging\n" "import logging.config\n" "import logging.handlers\n" "from multiprocessing import Process, Queue\n" "import random\n" "import threading\n" "import time\n" "\n" "def logger_thread(q):\n" " while True:\n" " record = q.get()\n" " if record is None:\n" " break\n" " logger = logging.getLogger(record.name)\n" " logger.handle(record)\n" "\n" "\n" "def worker_process(q):\n" " qh = logging.handlers.QueueHandler(q)\n" " root = logging.getLogger()\n" " root.setLevel(logging.DEBUG)\n" " root.addHandler(qh)\n" " levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" " logging.CRITICAL]\n" " loggers = ['foo', 'foo.bar', 'foo.bar.baz',\n" " 'spam', 'spam.ham', 'spam.ham.eggs']\n" " for i in range(100):\n" " lvl = random.choice(levels)\n" " logger = logging.getLogger(random.choice(loggers))\n" " logger.log(lvl, 'Message no. %d', i)\n" "\n" "if __name__ == '__main__':\n" " q = Queue()\n" " d = {\n" " 'version': 1,\n" " 'formatters': {\n" " 'detailed': {\n" " 'class': 'logging.Formatter',\n" " 'format': '%(asctime)s %(name)-15s %(levelname)-8s " "%(processName)-10s %(message)s'\n" " }\n" " },\n" " 'handlers': {\n" " 'console': {\n" " 'class': 'logging.StreamHandler',\n" " 'level': 'INFO',\n" " },\n" " 'file': {\n" " 'class': 'logging.FileHandler',\n" " 'filename': 'mplog.log',\n" " 'mode': 'w',\n" " 'formatter': 'detailed',\n" " },\n" " 'foofile': {\n" " 'class': 'logging.FileHandler',\n" " 'filename': 'mplog-foo.log',\n" " 'mode': 'w',\n" " 'formatter': 'detailed',\n" " },\n" " 'errors': {\n" " 'class': 'logging.FileHandler',\n" " 'filename': 'mplog-errors.log',\n" " 'mode': 'w',\n" " 'level': 'ERROR',\n" " 'formatter': 'detailed',\n" " },\n" " },\n" " 'loggers': {\n" " 'foo': {\n" " 'handlers': ['foofile']\n" " }\n" " },\n" " 'root': {\n" " 'level': 'DEBUG',\n" " 'handlers': ['console', 'file', 'errors']\n" " },\n" " }\n" " workers = []\n" " for i in range(5):\n" " wp = Process(target=worker_process, name='worker %d' % (i + 1), " "args=(q,))\n" " workers.append(wp)\n" " wp.start()\n" " logging.config.dictConfig(d)\n" " lp = threading.Thread(target=logger_thread, args=(q,))\n" " lp.start()\n" " # At this point, the main process could do some useful work of its own\n" " # Once it's done that, it can wait for the workers to terminate...\n" " for wp in workers:\n" " wp.join()\n" " # And now tell the logging thread to finish up, too\n" " q.put(None)\n" " lp.join()" msgstr "" #: ../../howto/logging-cookbook.rst:1512 msgid "" "This variant shows how you can e.g. apply configuration for particular " "loggers - e.g. the ``foo`` logger has a special handler which stores all " "events in the ``foo`` subsystem in a file ``mplog-foo.log``. This will be " "used by the logging machinery in the main process (even though the logging " "events are generated in the worker processes) to direct the messages to the " "appropriate destinations." msgstr "" "こちらは特定の logger に設定を適用する例になっています。``foo`` logger は " "``foo`` サブシステムの中の全てのイベントを ``mplog-foo.log`` に保存する特別" "な handler を持っています。これはメインプロセス側の log 処理で使われ、" "(logging イベントは worker プロセス側で生成されますが) 各メッセージを適切な出" "力先に出力します。" #: ../../howto/logging-cookbook.rst:1519 msgid "Using concurrent.futures.ProcessPoolExecutor" msgstr "concurrent.futures.ProcessPoolExecutorの利用" #: ../../howto/logging-cookbook.rst:1521 msgid "" "If you want to use :class:`concurrent.futures.ProcessPoolExecutor` to start " "your worker processes, you need to create the queue slightly differently. " "Instead of" msgstr "" "もし、ワーカープロセスを起動するために :class:`concurrent.futures." "ProcessPoolExecutor` を使いたいのであれば、少し違う方法でキューを作る必要があ" "ります。次のような方法の代わりに" #: ../../howto/logging-cookbook.rst:1525 msgid "queue = multiprocessing.Queue(-1)" msgstr "" #: ../../howto/logging-cookbook.rst:1529 msgid "you should use" msgstr "次のコードを利用する必要があります" #: ../../howto/logging-cookbook.rst:1531 msgid "" "queue = multiprocessing.Manager().Queue(-1) # also works with the examples " "above" msgstr "" #: ../../howto/logging-cookbook.rst:1535 msgid "and you can then replace the worker creation from this::" msgstr "そして、次のようなワーカー作成コードがあったとすると::" #: ../../howto/logging-cookbook.rst:1537 msgid "" "workers = []\n" "for i in range(10):\n" " worker = multiprocessing.Process(target=worker_process,\n" " args=(queue, worker_configurer))\n" " workers.append(worker)\n" " worker.start()\n" "for w in workers:\n" " w.join()" msgstr "" #: ../../howto/logging-cookbook.rst:1546 msgid "to this (remembering to first import :mod:`concurrent.futures`)::" msgstr "" "次のように変更します(最初に :mod:`concurrent.futures` をインポートするのを忘" "れないようにしましょう)::" #: ../../howto/logging-cookbook.rst:1548 msgid "" "with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:\n" " for i in range(10):\n" " executor.submit(worker_process, queue, worker_configurer)" msgstr "" #: ../../howto/logging-cookbook.rst:1553 msgid "Deploying Web applications using Gunicorn and uWSGI" msgstr "Gunicorn と uWSGI を用いた Web アプリケーションのデプロイ" #: ../../howto/logging-cookbook.rst:1555 msgid "" "When deploying Web applications using `Gunicorn `_ or " "`uWSGI `_ (or similar), " "multiple worker processes are created to handle client requests. In such " "environments, avoid creating file-based handlers directly in your web " "application. Instead, use a :class:`SocketHandler` to log from the web " "application to a listener in a separate process. This can be set up using a " "process management tool such as Supervisor - see `Running a logging socket " "listener in production`_ for more details." msgstr "" "`Gunicorn `_ や `uWSGI `_ (またはそれに類するもの) を使って Web アプリケー" "ションをデプロイする場合、クライアントのリクエストを処理するために複数のワー" "カープロセスが作られます。そのような環境では、 web アプリケーションに直接ファ" "イルベースのハンドラを作ることは避けてください。 代わりに、 :class:" "`SocketHandler` を使って別のプロセスとして動作するリスナーに web アプリケー" "ションからログを送信するようにしてください。これは Supervisor のようなプロセ" "ス管理ツールを使うことで設定できます - 詳しくは `作成中のロギングソケットの" "リスナーを実行する`_ を参照してください。" #: ../../howto/logging-cookbook.rst:1565 msgid "Using file rotation" msgstr "ファイルをローテートする" #: ../../howto/logging-cookbook.rst:1570 msgid "" "Sometimes you want to let a log file grow to a certain size, then open a new " "file and log to that. You may want to keep a certain number of these files, " "and when that many files have been created, rotate the files so that the " "number of files and the size of the files both remain bounded. For this " "usage pattern, the logging package provides a :class:`RotatingFileHandler`::" msgstr "" "ログファイルがある大きさに達したら、新しいファイルを開いてそこにログを取りた" "いことがあります。そのファイルをある数だけ残し、その数のファイルが生成された" "らファイルを循環し、ファイルの数も大きさも制限したいこともあるでしょう。この" "利用パターンのために、 logging パッケージは :class:`RotatingFileHandler` を提" "供しています::" #: ../../howto/logging-cookbook.rst:1576 msgid "" "import glob\n" "import logging\n" "import logging.handlers\n" "\n" "LOG_FILENAME = 'logging_rotatingfile_example.out'\n" "\n" "# Set up a specific logger with our desired output level\n" "my_logger = logging.getLogger('MyLogger')\n" "my_logger.setLevel(logging.DEBUG)\n" "\n" "# Add the log message handler to the logger\n" "handler = logging.handlers.RotatingFileHandler(\n" " LOG_FILENAME, maxBytes=20, backupCount=5)\n" "\n" "my_logger.addHandler(handler)\n" "\n" "# Log some messages\n" "for i in range(20):\n" " my_logger.debug('i = %d' % i)\n" "\n" "# See what files are created\n" "logfiles = glob.glob('%s*' % LOG_FILENAME)\n" "\n" "for filename in logfiles:\n" " print(filename)" msgstr "" #: ../../howto/logging-cookbook.rst:1602 msgid "" "The result should be 6 separate files, each with part of the log history for " "the application:" msgstr "" "この結果として、アプリケーションのログ履歴の一部である、6 つに別れたファイル" "が得られます:" #: ../../howto/logging-cookbook.rst:1605 msgid "" "logging_rotatingfile_example.out\n" "logging_rotatingfile_example.out.1\n" "logging_rotatingfile_example.out.2\n" "logging_rotatingfile_example.out.3\n" "logging_rotatingfile_example.out.4\n" "logging_rotatingfile_example.out.5" msgstr "" #: ../../howto/logging-cookbook.rst:1614 msgid "" "The most current file is always :file:`logging_rotatingfile_example.out`, " "and each time it reaches the size limit it is renamed with the suffix " "``.1``. Each of the existing backup files is renamed to increment the suffix " "(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased." msgstr "" "最新のファイルはいつでも :file:`logging_rotatingfile_example.out` で、サイズ" "の上限に達するたびに拡張子 ``.1`` を付けた名前に改名されます。既にあるバック" "アップファイルはその拡張子がインクリメントされ (``.1`` が ``.2`` になるな" "ど)、 ``.6`` ファイルは消去されます。" #: ../../howto/logging-cookbook.rst:1619 msgid "" "Obviously this example sets the log length much too small as an extreme " "example. You would want to set *maxBytes* to an appropriate value." msgstr "" "明らかに、ここでは極端な例示のためにファイルの大きさをかなり小さな値に設定し" "ています。実際に使うときは *maxBytes* を適切な値に設定してください。" #: ../../howto/logging-cookbook.rst:1627 msgid "Use of alternative formatting styles" msgstr "別の format スタイルを利用する" #: ../../howto/logging-cookbook.rst:1629 msgid "" "When logging was added to the Python standard library, the only way of " "formatting messages with variable content was to use the %-formatting " "method. Since then, Python has gained two new formatting approaches: :class:" "`string.Template` (added in Python 2.4) and :meth:`str.format` (added in " "Python 2.6)." msgstr "" "logging が Python 標準ライブラリに追加された時、メッセージを動的な内容で" "フォーマットする唯一の方法は % を使ったフォーマットでした。その後、 Python に" "は新しい文字列フォーマット機構として :class:`string.Template` (Python 2.4 で" "追加) と :meth:`str.format` (Python 2.6 で追加) が加わりました。" #: ../../howto/logging-cookbook.rst:1635 msgid "" "Logging (as of 3.2) provides improved support for these two additional " "formatting styles. The :class:`Formatter` class been enhanced to take an " "additional, optional keyword parameter named ``style``. This defaults to " "``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond " "to the other two formatting styles. Backwards compatibility is maintained by " "default (as you would expect), but by explicitly specifying a style " "parameter, you get the ability to specify format strings which work with :" "meth:`str.format` or :class:`string.Template`. Here's an example console " "session to show the possibilities:" msgstr "" "logging は (3.2 から) この2つの追加されたフォーマット方法をサポートしていま" "す。 :class:`Formatter` クラスが ``style`` という名前のオプションのキーワード" "引数を受け取ります。このデフォルト値は ``'%'`` ですが、他に ``'{'`` と " "``'$'`` が指定可能で、それぞれのフォーマット方法に対応しています。後方互換性" "はデフォルト値によって維持されていますが、明示的に style 引数を指定すること" "で、 :meth:`str.format` か :class:`string.Template` を使った format を指定す" "る事ができます。次の例はこの機能を使ってみています:" #: ../../howto/logging-cookbook.rst:1645 msgid "" ">>> import logging\n" ">>> root = logging.getLogger()\n" ">>> root.setLevel(logging.DEBUG)\n" ">>> handler = logging.StreamHandler()\n" ">>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',\n" "... style='{')\n" ">>> handler.setFormatter(bf)\n" ">>> root.addHandler(handler)\n" ">>> logger = logging.getLogger('foo.bar')\n" ">>> logger.debug('This is a DEBUG message')\n" "2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message\n" ">>> logger.critical('This is a CRITICAL message')\n" "2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message\n" ">>> df = logging.Formatter('$asctime $name ${levelname} $message',\n" "... style='$')\n" ">>> handler.setFormatter(df)\n" ">>> logger.debug('This is a DEBUG message')\n" "2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message\n" ">>> logger.critical('This is a CRITICAL message')\n" "2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message\n" ">>>" msgstr "" #: ../../howto/logging-cookbook.rst:1669 msgid "" "Note that the formatting of logging messages for final output to logs is " "completely independent of how an individual logging message is constructed. " "That can still use %-formatting, as shown here::" msgstr "" "最終的に出力されるログメッセージの format と、各メッセージを生成する部分は完" "全に独立していることに注意してください。次の例でわかるように、メッセージを生" "成する部分では % を使い続けています::" #: ../../howto/logging-cookbook.rst:1673 msgid "" ">>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')\n" "2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message\n" ">>>" msgstr "" #: ../../howto/logging-cookbook.rst:1677 msgid "" "Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take " "positional parameters for the actual logging message itself, with keyword " "parameters used only for determining options for how to handle the actual " "logging call (e.g. the ``exc_info`` keyword parameter to indicate that " "traceback information should be logged, or the ``extra`` keyword parameter " "to indicate additional contextual information to be added to the log). So " "you cannot directly make logging calls using :meth:`str.format` or :class:" "`string.Template` syntax, because internally the logging package uses %-" "formatting to merge the format string and the variable arguments. There " "would be no changing this while preserving backward compatibility, since all " "logging calls which are out there in existing code will be using %-format " "strings." msgstr "" "logging の呼び出し (``logger.debug()`` や ``logger.info()`` など) は、ログ" "メッセージのために位置引数しか受け取らず、キーワード引数はそれを処理するとき" "のオプションを指定するためだけに使われます。 (例えば、 ``exc_info`` キーワー" "ド引数を使ってログを取るトレースバック情報を指定したり、 ``extra`` キーワード" "引数を使ってログに付与する追加のコンテキスト情報を指定します。) logging パッ" "ケージは内部で % を使って format 文字列と引数をマージしているので、 :meth:" "`str.format` や :class:`string.Template` を使って logging を呼び出す事はでき" "ません。既存の logging 呼び出しは %-format を使っているので、後方互換性のため" "にこの部分を変更することはできません。" #: ../../howto/logging-cookbook.rst:1690 msgid "" "There is, however, a way that you can use {}- and $- formatting to construct " "your individual log messages. Recall that for a message you can use an " "arbitrary object as a message format string, and that the logging package " "will call ``str()`` on that object to get the actual format string. Consider " "the following two classes::" msgstr "" "しかし、{} や $ を使ってログメッセージをフォーマットする方法はあります。ログ" "メッセージには任意のオブジェクトを format 文字列として渡すことができ、" "logging パッケージはそのオブジェクトに対して ``str()`` を使って実際の format " "文字列を生成します。次の2つのクラスを見てください::" #: ../../howto/logging-cookbook.rst:1696 ../../howto/logging-cookbook.rst:2784 msgid "" "class BraceMessage:\n" " def __init__(self, fmt, /, *args, **kwargs):\n" " self.fmt = fmt\n" " self.args = args\n" " self.kwargs = kwargs\n" "\n" " def __str__(self):\n" " return self.fmt.format(*self.args, **self.kwargs)\n" "\n" "class DollarMessage:\n" " def __init__(self, fmt, /, **kwargs):\n" " self.fmt = fmt\n" " self.kwargs = kwargs\n" "\n" " def __str__(self):\n" " from string import Template\n" " return Template(self.fmt).substitute(**self.kwargs)" msgstr "" #: ../../howto/logging-cookbook.rst:1714 msgid "" "Either of these can be used in place of a format string, to allow {}- or $-" "formatting to be used to build the actual \"message\" part which appears in " "the formatted log output in place of \"%(message)s\" or \"{message}\" or " "\"$message\". It's a little unwieldy to use the class names whenever you " "want to log something, but it's quite palatable if you use an alias such as " "__ (double underscore --- not to be confused with _, the single underscore " "used as a synonym/alias for :func:`gettext.gettext` or its brethren)." msgstr "" "どちらのクラスも format 文字列の代わりに利用して、 {} や $ を使って実際のログ" "の \"%(message)s\", \"{message}\", \"$message\" で指定された \"message\" 部分" "を生成することができます。これは何かログを取りたいときに常に使うには使いにく" "いクラス名ですが、 __ (アンダースコア2つ --- :func:`gettext.gettext` やその仲" "間によくエイリアスとして使われるアンダースコア1つと混同しないように) などの使" "いやすいエイリアスを使うことができます。" #: ../../howto/logging-cookbook.rst:1722 msgid "" "The above classes are not included in Python, though they're easy enough to " "copy and paste into your own code. They can be used as follows (assuming " "that they're declared in a module called ``wherever``):" msgstr "" "上のクラスは Python には含まれませんが、自分のコードにコピペして使うのは簡単" "です。これらは次の例のようにして利用できます。(上のクラスが ``wherever`` とい" "うモジュールで定義されていると仮定します):" #: ../../howto/logging-cookbook.rst:1726 msgid "" ">>> from wherever import BraceMessage as __\n" ">>> print(__('Message with {0} {name}', 2, name='placeholders'))\n" "Message with 2 placeholders\n" ">>> class Point: pass\n" "...\n" ">>> p = Point()\n" ">>> p.x = 0.5\n" ">>> p.y = 0.5\n" ">>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',\n" "... point=p))\n" "Message with coordinates: (0.50, 0.50)\n" ">>> from wherever import DollarMessage as __\n" ">>> print(__('Message with $num $what', num=2, what='placeholders'))\n" "Message with 2 placeholders\n" ">>>" msgstr "" #: ../../howto/logging-cookbook.rst:1744 msgid "" "While the above examples use ``print()`` to show how the formatting works, " "you would of course use ``logger.debug()`` or similar to actually log using " "this approach." msgstr "" "上の例ではフォーマットの動作を示すために ``print()`` を使っていますが、もちろ" "ん実際にこの方法でログを出力するには ``logger.debug()`` などを使います。" #: ../../howto/logging-cookbook.rst:1748 msgid "" "One thing to note is that you pay no significant performance penalty with " "this approach: the actual formatting happens not when you make the logging " "call, but when (and if) the logged message is actually about to be output to " "a log by a handler. So the only slightly unusual thing which might trip you " "up is that the parentheses go around the format string and the arguments, " "not just the format string. That's because the __ notation is just syntax " "sugar for a constructor call to one of the :samp:`{XXX}Message` classes." msgstr "" "注意点として、この方法には大きなパフォーマンスのペナルティはありません。実際" "のフォーマット操作は logging の呼び出し時ではなくて、メッセージが実際に " "handler によって出力されるときに起こります。(出力されないならフォーマットもさ" "れません) そのため、この方法で注意しないといけないのは、追加の括弧が書式文字" "列だけではなく引数も囲わないといけないことだけです。これは __ が :samp:`{XXX}" "Message` クラスのコンストラクタ呼び出しのシンタックスシュガーでしか無いからで" "す。" #: ../../howto/logging-cookbook.rst:1756 msgid "" "If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar " "effect to the above, as in the following example::" msgstr "" "次の例のように、 :class:`LoggerAdapter` を利用して上と似たような効果を実現す" "る方法もあります::" #: ../../howto/logging-cookbook.rst:1759 msgid "" "import logging\n" "\n" "class Message:\n" " def __init__(self, fmt, args):\n" " self.fmt = fmt\n" " self.args = args\n" "\n" " def __str__(self):\n" " return self.fmt.format(*self.args)\n" "\n" "class StyleAdapter(logging.LoggerAdapter):\n" " def log(self, level, msg, /, *args, stacklevel=1, **kwargs):\n" " if self.isEnabledFor(level):\n" " msg, kwargs = self.process(msg, kwargs)\n" " self.logger.log(level, Message(msg, args), **kwargs,\n" " stacklevel=stacklevel+1)\n" "\n" "logger = StyleAdapter(logging.getLogger(__name__))\n" "\n" "def main():\n" " logger.debug('Hello, {}', 'world!')\n" "\n" "if __name__ == '__main__':\n" " logging.basicConfig(level=logging.DEBUG)\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:1785 msgid "" "The above script should log the message ``Hello, world!`` when run with " "Python 3.8 or later." msgstr "" "上のスクリプトは Python 3.8 以降では ``Hello, world!`` というメッセージをログ" "するはずです。" #: ../../howto/logging-cookbook.rst:1794 msgid "Customizing ``LogRecord``" msgstr "``LogRecord`` のカスタマイズ" #: ../../howto/logging-cookbook.rst:1796 msgid "" "Every logging event is represented by a :class:`LogRecord` instance. When an " "event is logged and not filtered out by a logger's level, a :class:" "`LogRecord` is created, populated with information about the event and then " "passed to the handlers for that logger (and its ancestors, up to and " "including the logger where further propagation up the hierarchy is " "disabled). Before Python 3.2, there were only two places where this creation " "was done:" msgstr "" "全ての logging イベントは :class:`LogRecord` のインスタンスとして表現されま" "す。イベントのログが取られて logger のレベルでフィルタされなかった場合、イベ" "ントの情報を含む :class:`LogRecord` が生成され、その logger (と、 propagate " "が無効になるまでの上位 logger) の handler に渡されます。 Python 3.2 までは、" "この生成が行われているのは2箇所だけでした:" #: ../../howto/logging-cookbook.rst:1803 msgid "" ":meth:`Logger.makeRecord`, which is called in the normal process of logging " "an event. This invoked :class:`LogRecord` directly to create an instance." msgstr "" ":meth:`Logger.makeRecord`: 通常のイベント logging プロセスで呼ばれます。これ" "は :class:`LogRecord` を直接読んでインスタンスを生成します。" #: ../../howto/logging-cookbook.rst:1806 msgid "" ":func:`makeLogRecord`, which is called with a dictionary containing " "attributes to be added to the LogRecord. This is typically invoked when a " "suitable dictionary has been received over the network (e.g. in pickle form " "via a :class:`~handlers.SocketHandler`, or in JSON form via an :class:" "`~handlers.HTTPHandler`)." msgstr "" ":func:`makeLogRecord`: LogRecord に追加される属性を含む辞書を渡して呼び出され" "ます。これはネットワーク越しに (pickle 形式で :class:`~handlers." "SocketHandler` 経由で、あるいは JSON 形式で :class:`~handlers.HTTPHandler` 経" "由で) 辞書を受け取った場合などに利用されます。" #: ../../howto/logging-cookbook.rst:1812 msgid "" "This has usually meant that if you need to do anything special with a :class:" "`LogRecord`, you've had to do one of the following." msgstr "" "そのために :class:`LogRecord` で何か特別なことをしたい場合は、次のどちらかを" "しなければなりません。" #: ../../howto/logging-cookbook.rst:1815 msgid "" "Create your own :class:`Logger` subclass, which overrides :meth:`Logger." "makeRecord`, and set it using :func:`~logging.setLoggerClass` before any " "loggers that you care about are instantiated." msgstr "" ":meth:`Logger.makeRecord` をオーバーライドした独自の :class:`Logger` のサブク" "ラスを作り、利用したい logger のどれかがインスタンス化される前に、それを :" "func:`~logging.setLoggerClass` を使って登録する。" #: ../../howto/logging-cookbook.rst:1818 msgid "" "Add a :class:`Filter` to a logger or handler, which does the necessary " "special manipulation you need when its :meth:`~Filter.filter` method is " "called." msgstr "" ":meth:`~Filter.filter` メソッドで必要な特殊な処理を行う :class:`Filter` を " "logger か handler に追加する。" #: ../../howto/logging-cookbook.rst:1822 msgid "" "The first approach would be a little unwieldy in the scenario where (say) " "several different libraries wanted to do different things. Each would " "attempt to set its own :class:`Logger` subclass, and the one which did this " "last would win." msgstr "" "最初の方法は、複数の異なるライブラリが別々のことをしようとした場合にうまく行" "きません。各ライブラリが独自の :class:`Logger` のサブクラスを登録しようとし" "て、最後に登録されたライブラリが生き残ります。" #: ../../howto/logging-cookbook.rst:1827 msgid "" "The second approach works reasonably well for many cases, but does not allow " "you to e.g. use a specialized subclass of :class:`LogRecord`. Library " "developers can set a suitable filter on their loggers, but they would have " "to remember to do this every time they introduced a new logger (which they " "would do simply by adding new packages or modules and doing ::" msgstr "" "2つ目の方法はほとんどのケースでうまくいきますが、たとえば :class:`LogRecord` " "を特殊化したサブクラスを使うことなどはできません。ライブラリの開発者は利用し" "ている logger に適切な filter を設定できますが、新しい logger を作るたびに忘" "れずに設定しないといけなくなります。 (新しいパッケージやモジュールを追加し、" "モジュールレベルで次の式を実行することで、新しい logger が作られます) ::" #: ../../howto/logging-cookbook.rst:1833 msgid "logger = logging.getLogger(__name__)" msgstr "" #: ../../howto/logging-cookbook.rst:1835 msgid "" "at module level). It's probably one too many things to think about. " "Developers could also add the filter to a :class:`~logging.NullHandler` " "attached to their top-level logger, but this would not be invoked if an " "application developer attached a handler to a lower-level library logger --- " "so output from that handler would not reflect the intentions of the library " "developer." msgstr "" "これでは考えることが余計に1つ増えてしまうでしょう。開発者は、最も高いレベルの" "ロガーに取り付けられた :class:`~logging.NullHandler` に、フィルタを追加するこ" "ともできますが、アプリケーション開発者が、より低いレベルに対するライブラリの" "ロガーにハンドラを取り付けた場合、フィルタは呼び出されません --- 従って、その" "ハンドラからの出力はライブラリ開発者の意図を反映したものにはなりません。" #: ../../howto/logging-cookbook.rst:1841 msgid "" "In Python 3.2 and later, :class:`~logging.LogRecord` creation is done " "through a factory, which you can specify. The factory is just a callable you " "can set with :func:`~logging.setLogRecordFactory`, and interrogate with :" "func:`~logging.getLogRecordFactory`. The factory is invoked with the same " "signature as the :class:`~logging.LogRecord` constructor, as :class:" "`LogRecord` is the default setting for the factory." msgstr "" "Python 3.2 以降では、 :class:`~logging.LogRecord` の生成は、指定できるファク" "トリ経由になります。ファクトリは callable で、 :func:`~logging." "setLogRecordFactory` で登録でき、 :func:`~logging.getLogRecordFactory` で現在" "のファクトリを取得できます。ファクトリは :class:`~logging.LogRecord` コンスト" "ラクタと同じシグネチャで呼び出され、 :class:`LogRecord` がデフォルトのファク" "トリとして設定されています。" #: ../../howto/logging-cookbook.rst:1848 msgid "" "This approach allows a custom factory to control all aspects of LogRecord " "creation. For example, you could return a subclass, or just add some " "additional attributes to the record once created, using a pattern similar to " "this::" msgstr "" "このアプローチはカスタムのファクトリが LogRecord の生成のすべての面を制御でき" "るようにしています。たとえば、サブクラスを返したり、次のようなパターンを使っ" "て単に属性を追加することができます::" #: ../../howto/logging-cookbook.rst:1852 msgid "" "old_factory = logging.getLogRecordFactory()\n" "\n" "def record_factory(*args, **kwargs):\n" " record = old_factory(*args, **kwargs)\n" " record.custom_attribute = 0xdecafbad\n" " return record\n" "\n" "logging.setLogRecordFactory(record_factory)" msgstr "" "old_factory = logging.getLogRecordFactory()\n" "\n" "def record_factory(*args, **kwargs):\n" " record = old_factory(*args, **kwargs)\n" " record.custom_attribute = 0xdecafbad\n" " return record\n" "\n" "logging.setLogRecordFactory(record_factory)" #: ../../howto/logging-cookbook.rst:1861 msgid "" "This pattern allows different libraries to chain factories together, and as " "long as they don't overwrite each other's attributes or unintentionally " "overwrite the attributes provided as standard, there should be no surprises. " "However, it should be borne in mind that each link in the chain adds run-" "time overhead to all logging operations, and the technique should only be " "used when the use of a :class:`Filter` does not provide the desired result." msgstr "" "このアプローチでは複数の異なるライブラリがファクトリをチェインさせて、お互い" "に同じ属性を上書きしたり、標準で提供されている属性を意図せず上書きしない限り" "はうまくいきます。しかし、チェインのつながり全てが、全ての logging の操作に対" "しての実行時のオーバーヘッドになることを念頭に置き、このテクニックは :class:" "`Filter` を利用するだけでは望む結果が得られない場合にのみ使うべきです。" #: ../../howto/logging-cookbook.rst:1873 msgid "Subclassing QueueHandler and QueueListener- a ZeroMQ example" msgstr "" #: ../../howto/logging-cookbook.rst:1876 ../../howto/logging-cookbook.rst:2009 msgid "Subclass ``QueueHandler``" msgstr "" #: ../../howto/logging-cookbook.rst:1878 msgid "" "You can use a :class:`QueueHandler` subclass to send messages to other kinds " "of queues, for example a ZeroMQ 'publish' socket. In the example below,the " "socket is created separately and passed to the handler (as its 'queue')::" msgstr "" ":class:`QueueHandler` のサブクラスを作ってメッセージを他のキュー、例えば " "ZeroMQ の 'publish' ソケットに送信することができます。下の例では、ソケットを" "別に作ってそれを handler に ('queue' として) 渡します::" #: ../../howto/logging-cookbook.rst:1882 msgid "" "import zmq # using pyzmq, the Python binding for ZeroMQ\n" "import json # for serializing records portably\n" "\n" "ctx = zmq.Context()\n" "sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value\n" "sock.bind('tcp://*:5556') # or wherever\n" "\n" "class ZeroMQSocketHandler(QueueHandler):\n" " def enqueue(self, record):\n" " self.queue.send_json(record.__dict__)\n" "\n" "\n" "handler = ZeroMQSocketHandler(sock)" msgstr "" #: ../../howto/logging-cookbook.rst:1897 msgid "" "Of course there are other ways of organizing this, for example passing in " "the data needed by the handler to create the socket::" msgstr "" "もちろん同じことを別の設計でもできます。socket を作るのに必要な情報を " "handler に渡す例です::" #: ../../howto/logging-cookbook.rst:1900 msgid "" "class ZeroMQSocketHandler(QueueHandler):\n" " def __init__(self, uri, socktype=zmq.PUB, ctx=None):\n" " self.ctx = ctx or zmq.Context()\n" " socket = zmq.Socket(self.ctx, socktype)\n" " socket.bind(uri)\n" " super().__init__(socket)\n" "\n" " def enqueue(self, record):\n" " self.queue.send_json(record.__dict__)\n" "\n" " def close(self):\n" " self.queue.close()" msgstr "" #: ../../howto/logging-cookbook.rst:1915 ../../howto/logging-cookbook.rst:1945 msgid "Subclass ``QueueListener``" msgstr "" #: ../../howto/logging-cookbook.rst:1917 msgid "" "You can also subclass :class:`QueueListener` to get messages from other " "kinds of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::" msgstr "" ":class:`QueueListener` のサブクラスを作って、メッセージを他のキュー、例えば " "ZeroMQ の 'subscribe' ソケットから取得する事もできます。サンプルです::" #: ../../howto/logging-cookbook.rst:1920 msgid "" "class ZeroMQSocketListener(QueueListener):\n" " def __init__(self, uri, /, *handlers, **kwargs):\n" " self.ctx = kwargs.get('ctx') or zmq.Context()\n" " socket = zmq.Socket(self.ctx, zmq.SUB)\n" " socket.setsockopt_string(zmq.SUBSCRIBE, '') # subscribe to " "everything\n" " socket.connect(uri)\n" " super().__init__(socket, *handlers, **kwargs)\n" "\n" " def dequeue(self):\n" " msg = self.queue.recv_json()\n" " return logging.makeLogRecord(msg)" msgstr "" #: ../../howto/logging-cookbook.rst:1935 msgid "Subclassing QueueHandler and QueueListener- a ``pynng`` example" msgstr "" #: ../../howto/logging-cookbook.rst:1937 msgid "" "In a similar way to the above section, we can implement a listener and " "handler using :pypi:`pynng`, which is a Python binding to `NNG `_, billed as a spiritual successor to ZeroMQ. The following " "snippets illustrate -- you can test them in an environment which has " "``pynng`` installed. Just for variety, we present the listener first." msgstr "" #: ../../howto/logging-cookbook.rst:1947 msgid "" "# listener.py\n" "import json\n" "import logging\n" "import logging.handlers\n" "\n" "import pynng\n" "\n" "DEFAULT_ADDR = \"tcp://localhost:13232\"\n" "\n" "interrupted = False\n" "\n" "class NNGSocketListener(logging.handlers.QueueListener):\n" "\n" " def __init__(self, uri, /, *handlers, **kwargs):\n" " # Have a timeout for interruptability, and open a\n" " # subscriber socket\n" " socket = pynng.Sub0(listen=uri, recv_timeout=500)\n" " # The b'' subscription matches all topics\n" " topics = kwargs.pop('topics', None) or b''\n" " socket.subscribe(topics)\n" " # We treat the socket as a queue\n" " super().__init__(socket, *handlers, **kwargs)\n" "\n" " def dequeue(self, block):\n" " data = None\n" " # Keep looping while not interrupted and no data received over the\n" " # socket\n" " while not interrupted:\n" " try:\n" " data = self.queue.recv(block=block)\n" " break\n" " except pynng.Timeout:\n" " pass\n" " except pynng.Closed: # sometimes happens when you hit Ctrl-C\n" " break\n" " if data is None:\n" " return None\n" " # Get the logging event sent from a publisher\n" " event = json.loads(data.decode('utf-8'))\n" " return logging.makeLogRecord(event)\n" "\n" " def enqueue_sentinel(self):\n" " # Not used in this implementation, as the socket isn't really a\n" " # queue\n" " pass\n" "\n" "logging.getLogger('pynng').propagate = False\n" "listener = NNGSocketListener(DEFAULT_ADDR, logging.StreamHandler(), " "topics=b'')\n" "listener.start()\n" "print('Press Ctrl-C to stop.')\n" "try:\n" " while True:\n" " pass\n" "except KeyboardInterrupt:\n" " interrupted = True\n" "finally:\n" " listener.stop()" msgstr "" #: ../../howto/logging-cookbook.rst:2013 msgid "" "# sender.py\n" "import json\n" "import logging\n" "import logging.handlers\n" "import time\n" "import random\n" "\n" "import pynng\n" "\n" "DEFAULT_ADDR = \"tcp://localhost:13232\"\n" "\n" "class NNGSocketHandler(logging.handlers.QueueHandler):\n" "\n" " def __init__(self, uri):\n" " socket = pynng.Pub0(dial=uri, send_timeout=500)\n" " super().__init__(socket)\n" "\n" " def enqueue(self, record):\n" " # Send the record as UTF-8 encoded JSON\n" " d = dict(record.__dict__)\n" " data = json.dumps(d)\n" " self.queue.send(data.encode('utf-8'))\n" "\n" " def close(self):\n" " self.queue.close()\n" "\n" "logging.getLogger('pynng').propagate = False\n" "handler = NNGSocketHandler(DEFAULT_ADDR)\n" "# Make sure the process ID is in the output\n" "logging.basicConfig(level=logging.DEBUG,\n" " handlers=[logging.StreamHandler(), handler],\n" " format='%(levelname)-8s %(name)10s %(process)6s " "%(message)s')\n" "levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" " logging.CRITICAL)\n" "logger_names = ('myapp', 'myapp.lib1', 'myapp.lib2')\n" "msgno = 1\n" "while True:\n" " # Just randomly select some loggers and levels and log away\n" " level = random.choice(levels)\n" " logger = logging.getLogger(random.choice(logger_names))\n" " logger.log(level, 'Message no. %5d' % msgno)\n" " msgno += 1\n" " delay = random.random() * 2 + 0.5\n" " time.sleep(delay)" msgstr "" #: ../../howto/logging-cookbook.rst:2060 msgid "" "You can run the above two snippets in separate command shells. If we run the " "listener in one shell and run the sender in two separate shells, we should " "see something like the following. In the first sender shell:" msgstr "" #: ../../howto/logging-cookbook.rst:2064 msgid "" "$ python sender.py\n" "DEBUG myapp 613 Message no. 1\n" "WARNING myapp.lib2 613 Message no. 2\n" "CRITICAL myapp.lib2 613 Message no. 3\n" "WARNING myapp.lib2 613 Message no. 4\n" "CRITICAL myapp.lib1 613 Message no. 5\n" "DEBUG myapp 613 Message no. 6\n" "CRITICAL myapp.lib1 613 Message no. 7\n" "INFO myapp.lib1 613 Message no. 8\n" "(and so on)" msgstr "" #: ../../howto/logging-cookbook.rst:2077 msgid "In the second sender shell:" msgstr "" #: ../../howto/logging-cookbook.rst:2079 msgid "" "$ python sender.py\n" "INFO myapp.lib2 657 Message no. 1\n" "CRITICAL myapp.lib2 657 Message no. 2\n" "CRITICAL myapp 657 Message no. 3\n" "CRITICAL myapp.lib1 657 Message no. 4\n" "INFO myapp.lib1 657 Message no. 5\n" "WARNING myapp.lib2 657 Message no. 6\n" "CRITICAL myapp 657 Message no. 7\n" "DEBUG myapp.lib1 657 Message no. 8\n" "(and so on)" msgstr "" #: ../../howto/logging-cookbook.rst:2092 msgid "In the listener shell:" msgstr "" #: ../../howto/logging-cookbook.rst:2094 msgid "" "$ python listener.py\n" "Press Ctrl-C to stop.\n" "DEBUG myapp 613 Message no. 1\n" "WARNING myapp.lib2 613 Message no. 2\n" "INFO myapp.lib2 657 Message no. 1\n" "CRITICAL myapp.lib2 613 Message no. 3\n" "CRITICAL myapp.lib2 657 Message no. 2\n" "CRITICAL myapp 657 Message no. 3\n" "WARNING myapp.lib2 613 Message no. 4\n" "CRITICAL myapp.lib1 613 Message no. 5\n" "CRITICAL myapp.lib1 657 Message no. 4\n" "INFO myapp.lib1 657 Message no. 5\n" "DEBUG myapp 613 Message no. 6\n" "WARNING myapp.lib2 657 Message no. 6\n" "CRITICAL myapp 657 Message no. 7\n" "CRITICAL myapp.lib1 613 Message no. 7\n" "INFO myapp.lib1 613 Message no. 8\n" "DEBUG myapp.lib1 657 Message no. 8\n" "(and so on)" msgstr "" #: ../../howto/logging-cookbook.rst:2116 msgid "" "As you can see, the logging from the two sender processes is interleaved in " "the listener's output." msgstr "" #: ../../howto/logging-cookbook.rst:2121 msgid "An example dictionary-based configuration" msgstr "辞書ベースで構成する例" #: ../../howto/logging-cookbook.rst:2123 msgid "" "Below is an example of a logging configuration dictionary - it's taken from " "the `documentation on the Django project `_. This dictionary is passed to :" "func:`~config.dictConfig` to put the configuration into effect::" msgstr "" "次の例は辞書を使った logging の構成です。この例は `Django プロジェクトのド" "キュメント `_ から持ってきました。この辞書を :func:`~config." "dictConfig` に渡して設定を有効にします::" #: ../../howto/logging-cookbook.rst:2127 msgid "" "LOGGING = {\n" " 'version': 1,\n" " 'disable_existing_loggers': False,\n" " 'formatters': {\n" " 'verbose': {\n" " 'format': '{levelname} {asctime} {module} {process:d} {thread:d} " "{message}',\n" " 'style': '{',\n" " },\n" " 'simple': {\n" " 'format': '{levelname} {message}',\n" " 'style': '{',\n" " },\n" " },\n" " 'filters': {\n" " 'special': {\n" " '()': 'project.logging.SpecialFilter',\n" " 'foo': 'bar',\n" " },\n" " },\n" " 'handlers': {\n" " 'console': {\n" " 'level': 'INFO',\n" " 'class': 'logging.StreamHandler',\n" " 'formatter': 'simple',\n" " },\n" " 'mail_admins': {\n" " 'level': 'ERROR',\n" " 'class': 'django.utils.log.AdminEmailHandler',\n" " 'filters': ['special']\n" " }\n" " },\n" " 'loggers': {\n" " 'django': {\n" " 'handlers': ['console'],\n" " 'propagate': True,\n" " },\n" " 'django.request': {\n" " 'handlers': ['mail_admins'],\n" " 'level': 'ERROR',\n" " 'propagate': False,\n" " },\n" " 'myproject.custom': {\n" " 'handlers': ['console', 'mail_admins'],\n" " 'level': 'INFO',\n" " 'filters': ['special']\n" " }\n" " }\n" "}" msgstr "" #: ../../howto/logging-cookbook.rst:2176 msgid "" "For more information about this configuration, you can see the `relevant " "section `_ of the Django documentation." msgstr "" "この構成方法についてのより詳しい情報は、 Django のドキュメントの `該当のセク" "ション `_ で見ることができます。" #: ../../howto/logging-cookbook.rst:2183 msgid "Using a rotator and namer to customize log rotation processing" msgstr "rotator と namer を使ってログローテートをカスタマイズする" #: ../../howto/logging-cookbook.rst:2185 msgid "" "An example of how you can define a namer and rotator is given in the " "following runnable script, which shows gzip compression of the log file::" msgstr "" "namer と rotator を定義する方法の例は以下の実行可能なスクリプトに示されていま" "す。ここではログファイルを gzip により圧縮する例を示しています::" #: ../../howto/logging-cookbook.rst:2188 msgid "" "import gzip\n" "import logging\n" "import logging.handlers\n" "import os\n" "import shutil\n" "\n" "def namer(name):\n" " return name + \".gz\"\n" "\n" "def rotator(source, dest):\n" " with open(source, 'rb') as f_in:\n" " with gzip.open(dest, 'wb') as f_out:\n" " shutil.copyfileobj(f_in, f_out)\n" " os.remove(source)\n" "\n" "\n" "rh = logging.handlers.RotatingFileHandler('rotated.log', maxBytes=128, " "backupCount=5)\n" "rh.rotator = rotator\n" "rh.namer = namer\n" "\n" "root = logging.getLogger()\n" "root.setLevel(logging.INFO)\n" "root.addHandler(rh)\n" "f = logging.Formatter('%(asctime)s %(message)s')\n" "rh.setFormatter(f)\n" "for i in range(1000):\n" " root.info(f'Message no. {i + 1}')" msgstr "" #: ../../howto/logging-cookbook.rst:2216 msgid "" "After running this, you will see six new files, five of which are compressed:" msgstr "" "このスクリプトを実行すると、6つの新しいファイルが生成され、そのうち5つは圧縮" "されています:" #: ../../howto/logging-cookbook.rst:2218 msgid "" "$ ls rotated.log*\n" "rotated.log rotated.log.2.gz rotated.log.4.gz\n" "rotated.log.1.gz rotated.log.3.gz rotated.log.5.gz\n" "$ zcat rotated.log.1.gz\n" "2023-01-20 02:28:17,767 Message no. 996\n" "2023-01-20 02:28:17,767 Message no. 997\n" "2023-01-20 02:28:17,767 Message no. 998" msgstr "" #: ../../howto/logging-cookbook.rst:2229 msgid "A more elaborate multiprocessing example" msgstr "より手の込んだ multiprocessing の例" #: ../../howto/logging-cookbook.rst:2231 msgid "" "The following working example shows how logging can be used with " "multiprocessing using configuration files. The configurations are fairly " "simple, but serve to illustrate how more complex ones could be implemented " "in a real multiprocessing scenario." msgstr "" "次の実際に動作する例は、logging を multiprocessing と設定ファイルを使って利用" "する方法を示しています。設定内容はかなりシンプルですが、より複雑な構成を実際" "の multiprocessing を利用するシナリオで実装する方法を示しています。" #: ../../howto/logging-cookbook.rst:2236 msgid "" "In the example, the main process spawns a listener process and some worker " "processes. Each of the main process, the listener and the workers have three " "separate configurations (the workers all share the same configuration). We " "can see logging in the main process, how the workers log to a QueueHandler " "and how the listener implements a QueueListener and a more complex logging " "configuration, and arranges to dispatch events received via the queue to the " "handlers specified in the configuration. Note that these configurations are " "purely illustrative, but you should be able to adapt this example to your " "own scenario." msgstr "" "この例では、メインプロセスは listener プロセスといくつかのワーカープロセスを" "起動します。メイン、listener、ワーカープロセスはそれぞれ分離した設定を持って" "います (ワーカープロセス群は同じ設定を共有します)。この例から、メインプロセス" "の logging, ワーカーが QueueHandler でログを送っているところ、listener が利用" "する QueueListener の実装、複雑な設定、キューから受け取ったイベントを設定され" "た handler に分配する部分を見ることができます。この設定は説明用のものですが、" "この例を自分のシナリオに適応させることができるでしょう。" #: ../../howto/logging-cookbook.rst:2246 msgid "" "Here's the script - the docstrings and the comments hopefully explain how it " "works::" msgstr "これがそのスクリプトです。docstring とコメントで動作を説明しています::" #: ../../howto/logging-cookbook.rst:2249 msgid "" "import logging\n" "import logging.config\n" "import logging.handlers\n" "from multiprocessing import Process, Queue, Event, current_process\n" "import os\n" "import random\n" "import time\n" "\n" "class MyHandler:\n" " \"\"\"\n" " A simple handler for logging events. It runs in the listener process " "and\n" " dispatches events to loggers based on the name in the received record,\n" " which then get dispatched, by the logging system, to the handlers\n" " configured for those loggers.\n" " \"\"\"\n" "\n" " def handle(self, record):\n" " if record.name == \"root\":\n" " logger = logging.getLogger()\n" " else:\n" " logger = logging.getLogger(record.name)\n" "\n" " if logger.isEnabledFor(record.levelno):\n" " # The process name is transformed just to show that it's the " "listener\n" " # doing the logging to files and console\n" " record.processName = '%s (for %s)' % (current_process().name, " "record.processName)\n" " logger.handle(record)\n" "\n" "def listener_process(q, stop_event, config):\n" " \"\"\"\n" " This could be done in the main process, but is just done in a separate\n" " process for illustrative purposes.\n" "\n" " This initialises logging according to the specified configuration,\n" " starts the listener and waits for the main process to signal completion\n" " via the event. The listener is then stopped, and the process exits.\n" " \"\"\"\n" " logging.config.dictConfig(config)\n" " listener = logging.handlers.QueueListener(q, MyHandler())\n" " listener.start()\n" " if os.name == 'posix':\n" " # On POSIX, the setup logger will have been configured in the\n" " # parent process, but should have been disabled following the\n" " # dictConfig call.\n" " # On Windows, since fork isn't used, the setup logger won't\n" " # exist in the child, so it would be created and the message\n" " # would appear - hence the \"if posix\" clause.\n" " logger = logging.getLogger('setup')\n" " logger.critical('Should not appear, because of disabled " "logger ...')\n" " stop_event.wait()\n" " listener.stop()\n" "\n" "def worker_process(config):\n" " \"\"\"\n" " A number of these are spawned for the purpose of illustration. In\n" " practice, they could be a heterogeneous bunch of processes rather than\n" " ones which are identical to each other.\n" "\n" " This initialises logging according to the specified configuration,\n" " and logs a hundred messages with random levels to randomly selected\n" " loggers.\n" "\n" " A small sleep is added to allow other processes a chance to run. This\n" " is not strictly needed, but it mixes the output from the different\n" " processes a bit more than if it's left out.\n" " \"\"\"\n" " logging.config.dictConfig(config)\n" " levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" " logging.CRITICAL]\n" " loggers = ['foo', 'foo.bar', 'foo.bar.baz',\n" " 'spam', 'spam.ham', 'spam.ham.eggs']\n" " if os.name == 'posix':\n" " # On POSIX, the setup logger will have been configured in the\n" " # parent process, but should have been disabled following the\n" " # dictConfig call.\n" " # On Windows, since fork isn't used, the setup logger won't\n" " # exist in the child, so it would be created and the message\n" " # would appear - hence the \"if posix\" clause.\n" " logger = logging.getLogger('setup')\n" " logger.critical('Should not appear, because of disabled " "logger ...')\n" " for i in range(100):\n" " lvl = random.choice(levels)\n" " logger = logging.getLogger(random.choice(loggers))\n" " logger.log(lvl, 'Message no. %d', i)\n" " time.sleep(0.01)\n" "\n" "def main():\n" " q = Queue()\n" " # The main process gets a simple configuration which prints to the " "console.\n" " config_initial = {\n" " 'version': 1,\n" " 'handlers': {\n" " 'console': {\n" " 'class': 'logging.StreamHandler',\n" " 'level': 'INFO'\n" " }\n" " },\n" " 'root': {\n" " 'handlers': ['console'],\n" " 'level': 'DEBUG'\n" " }\n" " }\n" " # The worker process configuration is just a QueueHandler attached to " "the\n" " # root logger, which allows all messages to be sent to the queue.\n" " # We disable existing loggers to disable the \"setup\" logger used in " "the\n" " # parent process. This is needed on POSIX because the logger will\n" " # be there in the child following a fork().\n" " config_worker = {\n" " 'version': 1,\n" " 'disable_existing_loggers': True,\n" " 'handlers': {\n" " 'queue': {\n" " 'class': 'logging.handlers.QueueHandler',\n" " 'queue': q\n" " }\n" " },\n" " 'root': {\n" " 'handlers': ['queue'],\n" " 'level': 'DEBUG'\n" " }\n" " }\n" " # The listener process configuration shows that the full flexibility of\n" " # logging configuration is available to dispatch events to handlers " "however\n" " # you want.\n" " # We disable existing loggers to disable the \"setup\" logger used in " "the\n" " # parent process. This is needed on POSIX because the logger will\n" " # be there in the child following a fork().\n" " config_listener = {\n" " 'version': 1,\n" " 'disable_existing_loggers': True,\n" " 'formatters': {\n" " 'detailed': {\n" " 'class': 'logging.Formatter',\n" " 'format': '%(asctime)s %(name)-15s %(levelname)-8s " "%(processName)-10s %(message)s'\n" " },\n" " 'simple': {\n" " 'class': 'logging.Formatter',\n" " 'format': '%(name)-15s %(levelname)-8s %(processName)-10s " "%(message)s'\n" " }\n" " },\n" " 'handlers': {\n" " 'console': {\n" " 'class': 'logging.StreamHandler',\n" " 'formatter': 'simple',\n" " 'level': 'INFO'\n" " },\n" " 'file': {\n" " 'class': 'logging.FileHandler',\n" " 'filename': 'mplog.log',\n" " 'mode': 'w',\n" " 'formatter': 'detailed'\n" " },\n" " 'foofile': {\n" " 'class': 'logging.FileHandler',\n" " 'filename': 'mplog-foo.log',\n" " 'mode': 'w',\n" " 'formatter': 'detailed'\n" " },\n" " 'errors': {\n" " 'class': 'logging.FileHandler',\n" " 'filename': 'mplog-errors.log',\n" " 'mode': 'w',\n" " 'formatter': 'detailed',\n" " 'level': 'ERROR'\n" " }\n" " },\n" " 'loggers': {\n" " 'foo': {\n" " 'handlers': ['foofile']\n" " }\n" " },\n" " 'root': {\n" " 'handlers': ['console', 'file', 'errors'],\n" " 'level': 'DEBUG'\n" " }\n" " }\n" " # Log some initial events, just to show that logging in the parent " "works\n" " # normally.\n" " logging.config.dictConfig(config_initial)\n" " logger = logging.getLogger('setup')\n" " logger.info('About to create workers ...')\n" " workers = []\n" " for i in range(5):\n" " wp = Process(target=worker_process, name='worker %d' % (i + 1),\n" " args=(config_worker,))\n" " workers.append(wp)\n" " wp.start()\n" " logger.info('Started worker: %s', wp.name)\n" " logger.info('About to create listener ...')\n" " stop_event = Event()\n" " lp = Process(target=listener_process, name='listener',\n" " args=(q, stop_event, config_listener))\n" " lp.start()\n" " logger.info('Started listener')\n" " # We now hang around for the workers to finish their work.\n" " for wp in workers:\n" " wp.join()\n" " # Workers all done, listening can now stop.\n" " # Logging in the parent still works normally.\n" " logger.info('Telling listener to stop ...')\n" " stop_event.set()\n" " lp.join()\n" " logger.info('All done.')\n" "\n" "if __name__ == '__main__':\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:2458 msgid "Inserting a BOM into messages sent to a SysLogHandler" msgstr "SysLogHandler に送るメッセージに BOM を挿入する" #: ../../howto/logging-cookbook.rst:2460 msgid "" ":rfc:`5424` requires that a Unicode message be sent to a syslog daemon as a " "set of bytes which have the following structure: an optional pure-ASCII " "component, followed by a UTF-8 Byte Order Mark (BOM), followed by Unicode " "encoded using UTF-8. (See the :rfc:`relevant section of the specification " "<5424#section-6>`.)" msgstr "" ":rfc:`5424` は syslog デーモンに Unicode メッセージを送る時、次の構造を要求し" "ています: オプショナルなピュア ASCII部分、続けて UTF-8 の Byte Order Mark " "(BOM)、続けて UTF-8 でエンコードされた Unicode. ( :rfc:`仕様の該当セクション " "<5424#section-6>` を参照)" #: ../../howto/logging-cookbook.rst:2466 msgid "" "In Python 3.1, code was added to :class:`~logging.handlers.SysLogHandler` to " "insert a BOM into the message, but unfortunately, it was implemented " "incorrectly, with the BOM appearing at the beginning of the message and " "hence not allowing any pure-ASCII component to appear before it." msgstr "" "Python 3.1 で :class:`~logging.handlers.SysLogHandler` に、 message に BOM を" "挿入するコードが追加されました。しかし、そのときの実装が悪くて、 message の先" "頭に BOM をつけてしまうのでピュアASCII 部分をその前に書くことができませんでし" "た。" #: ../../howto/logging-cookbook.rst:2472 msgid "" "As this behaviour is broken, the incorrect BOM insertion code is being " "removed from Python 3.2.4 and later. However, it is not being replaced, and " "if you want to produce :rfc:`5424`-compliant messages which include a BOM, " "an optional pure-ASCII sequence before it and arbitrary Unicode after it, " "encoded using UTF-8, then you need to do the following:" msgstr "" "この動作は壊れているので、Python 3.2.4 以降では BOM を挿入するコードが、削除" "されました。書き直されるのではなく削除されたので、 :rfc:`5424` 準拠の、BOM " "と、オプションのピュア ASCII部分をBOMの前に、任意の Unicode を BOM の後ろに持" "つ UTF-8 でエンコードされた message を生成したい場合、次の手順に従う必要があ" "ります:" #: ../../howto/logging-cookbook.rst:2478 msgid "" "Attach a :class:`~logging.Formatter` instance to your :class:`~logging." "handlers.SysLogHandler` instance, with a format string such as::" msgstr "" ":class:`~logging.handlers.SysLogHandler` のインスタンスに、次のような format " "文字列を持った :class:`~logging.Formatter` インスタンスをアタッチする::" #: ../../howto/logging-cookbook.rst:2482 msgid "'ASCII section\\ufeffUnicode section'" msgstr "" #: ../../howto/logging-cookbook.rst:2484 msgid "" "The Unicode code point U+FEFF, when encoded using UTF-8, will be encoded as " "a UTF-8 BOM -- the byte-string ``b'\\xef\\xbb\\xbf'``." msgstr "" "Unicode のコードポイント U+FEFF は、UTF-8 でエンコードすると BOM -- " "``b'\\xef\\xbb\\xbf'`` -- になります。" #: ../../howto/logging-cookbook.rst:2487 msgid "" "Replace the ASCII section with whatever placeholders you like, but make sure " "that the data that appears in there after substitution is always ASCII (that " "way, it will remain unchanged after UTF-8 encoding)." msgstr "" "ASCII セクションを好きなプレースホルダに変更する。ただしその部分の置換結果が" "常に ASCII になるように注意する(UTF-8 でエンコードされてもその部分が変化しな" "いようにする)。" #: ../../howto/logging-cookbook.rst:2491 msgid "" "Replace the Unicode section with whatever placeholders you like; if the data " "which appears there after substitution contains characters outside the ASCII " "range, that's fine -- it will be encoded using UTF-8." msgstr "" "Unicode セクションを任意のプレースホルダに置き換える。この部分を置換したデー" "タに ASCII 外の文字が含まれていても、それは単に UTF-8 でエンコードされるだけ" "です。" #: ../../howto/logging-cookbook.rst:2495 msgid "" "The formatted message *will* be encoded using UTF-8 encoding by " "``SysLogHandler``. If you follow the above rules, you should be able to " "produce :rfc:`5424`-compliant messages. If you don't, logging may not " "complain, but your messages will not be RFC 5424-compliant, and your syslog " "daemon may complain." msgstr "" "フォーマットされた message は ``SysLogHandler`` によって UTF-8 でエンコードさ" "れます。上のルールに従えば、RFC 5424 準拠のメッセージを生成できます。上のルー" "ルに従わない場合、logging は何もエラーを起こしませんが、message は :rfc:" "`5424` に準拠しない形で送られるので、syslog デーモン側で何かエラーが起こる可" "能性があります。" #: ../../howto/logging-cookbook.rst:2502 msgid "Implementing structured logging" msgstr "構造化ログを実装する" #: ../../howto/logging-cookbook.rst:2504 msgid "" "Although most logging messages are intended for reading by humans, and thus " "not readily machine-parseable, there might be circumstances where you want " "to output messages in a structured format which *is* capable of being parsed " "by a program (without needing complex regular expressions to parse the log " "message). This is straightforward to achieve using the logging package. " "There are a number of ways in which this could be achieved, but the " "following is a simple approach which uses JSON to serialise the event in a " "machine-parseable manner::" msgstr "" "多くのログメッセージは人間が読むために書かれるため、機械的に処理しにくくなっ" "ていますが、場合によっては (複雑な正規表現を使ってログメッセージをパースしな" "くても) プログラムがパース *できる* 構造化されたフォーマットでメッセージを出" "力したい場合があります。\n" "logging パッケージを使うと、これを簡単に実現できます。\n" "実現する方法は幾つもありますが、次の例は JSON を使ってイベントを、機械でパー" "スできる形にシリアライズする単純な方法です::" #: ../../howto/logging-cookbook.rst:2512 msgid "" "import json\n" "import logging\n" "\n" "class StructuredMessage:\n" " def __init__(self, message, /, **kwargs):\n" " self.message = message\n" " self.kwargs = kwargs\n" "\n" " def __str__(self):\n" " return '%s >>> %s' % (self.message, json.dumps(self.kwargs))\n" "\n" "_ = StructuredMessage # optional, to improve readability\n" "\n" "logging.basicConfig(level=logging.INFO, format='%(message)s')\n" "logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))" msgstr "" #: ../../howto/logging-cookbook.rst:2528 msgid "If the above script is run, it prints:" msgstr "上のスクリプトを実行すると次のように出力されます:" #: ../../howto/logging-cookbook.rst:2530 msgid "" "message 1 >>> {\"fnum\": 123.456, \"num\": 123, \"bar\": \"baz\", \"foo\": " "\"bar\"}" msgstr "" #: ../../howto/logging-cookbook.rst:2534 ../../howto/logging-cookbook.rst:2576 msgid "" "Note that the order of items might be different according to the version of " "Python used." msgstr "要素の順序は Python のバージョンによって異なることに注意してください。" #: ../../howto/logging-cookbook.rst:2537 msgid "" "If you need more specialised processing, you can use a custom JSON encoder, " "as in the following complete example::" msgstr "" "より特殊な処理が必要な場合、次の例のように、カスタムの JSON エンコーダを作る" "ことができます::" #: ../../howto/logging-cookbook.rst:2540 msgid "" "import json\n" "import logging\n" "\n" "\n" "class Encoder(json.JSONEncoder):\n" " def default(self, o):\n" " if isinstance(o, set):\n" " return tuple(o)\n" " elif isinstance(o, str):\n" " return o.encode('unicode_escape').decode('ascii')\n" " return super().default(o)\n" "\n" "class StructuredMessage:\n" " def __init__(self, message, /, **kwargs):\n" " self.message = message\n" " self.kwargs = kwargs\n" "\n" " def __str__(self):\n" " s = Encoder().encode(self.kwargs)\n" " return '%s >>> %s' % (self.message, s)\n" "\n" "_ = StructuredMessage # optional, to improve readability\n" "\n" "def main():\n" " logging.basicConfig(level=logging.INFO, format='%(message)s')\n" " logging.info(_('message 1', set_value={1, 2, 3}, snowman='\\u2603'))\n" "\n" "if __name__ == '__main__':\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:2570 msgid "When the above script is run, it prints:" msgstr "上のスクリプトを実行すると次のように出力されます:" #: ../../howto/logging-cookbook.rst:2572 msgid "message 1 >>> {\"snowman\": \"\\u2603\", \"set_value\": [1, 2, 3]}" msgstr "" #: ../../howto/logging-cookbook.rst:2585 msgid "Customizing handlers with :func:`dictConfig`" msgstr "handler を :func:`dictConfig` を使ってカスタマイズする" #: ../../howto/logging-cookbook.rst:2587 msgid "" "There are times when you want to customize logging handlers in particular " "ways, and if you use :func:`dictConfig` you may be able to do this without " "subclassing. As an example, consider that you may want to set the ownership " "of a log file. On POSIX, this is easily done using :func:`shutil.chown`, but " "the file handlers in the stdlib don't offer built-in support. You can " "customize handler creation using a plain function such as::" msgstr "" "logging handler に特定のカスタマイズを何度もしたい場合で、 :func:" "`dictConfig` を使っているなら、サブクラスを作らなくてもカスタマイズが可能で" "す。例えば、ログファイルの owner を設定したいとします。これは POSIX 環境で" "は :func:`shutil.chown` を使って簡単に実現できますが、標準ライブラリの file " "handler はこの機能を組み込みでサポートしていません。 handler の生成を通常の関" "数を使ってカスタマイズすることができます::" #: ../../howto/logging-cookbook.rst:2594 msgid "" "def owned_file_handler(filename, mode='a', encoding=None, owner=None):\n" " if owner:\n" " if not os.path.exists(filename):\n" " open(filename, 'a').close()\n" " shutil.chown(filename, *owner)\n" " return logging.FileHandler(filename, mode, encoding)" msgstr "" #: ../../howto/logging-cookbook.rst:2601 msgid "" "You can then specify, in a logging configuration passed to :func:" "`dictConfig`, that a logging handler be created by calling this function::" msgstr "" "そして、 :func:`dictConfig` に渡される構成設定の中で、この関数を使って " "logging handler を生成するように指定することができます::" #: ../../howto/logging-cookbook.rst:2604 msgid "" "LOGGING = {\n" " 'version': 1,\n" " 'disable_existing_loggers': False,\n" " 'formatters': {\n" " 'default': {\n" " 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'\n" " },\n" " },\n" " 'handlers': {\n" " 'file':{\n" " # The values below are popped from this dictionary and\n" " # used to create the handler, set the handler's level and\n" " # its formatter.\n" " '()': owned_file_handler,\n" " 'level':'DEBUG',\n" " 'formatter': 'default',\n" " # The values below are passed to the handler creator callable\n" " # as keyword arguments.\n" " 'owner': ['pulse', 'pulse'],\n" " 'filename': 'chowntest.log',\n" " 'mode': 'w',\n" " 'encoding': 'utf-8',\n" " },\n" " },\n" " 'root': {\n" " 'handlers': ['file'],\n" " 'level': 'DEBUG',\n" " },\n" "}" msgstr "" #: ../../howto/logging-cookbook.rst:2634 msgid "" "In this example I am setting the ownership using the ``pulse`` user and " "group, just for the purposes of illustration. Putting it together into a " "working script, ``chowntest.py``::" msgstr "" "この例は説明用のものですが、owner の user と group を ``pulse`` に設定してい" "ます。これを動くスクリプトに ``chowntest.py`` に組み込んでみます::" #: ../../howto/logging-cookbook.rst:2638 msgid "" "import logging, logging.config, os, shutil\n" "\n" "def owned_file_handler(filename, mode='a', encoding=None, owner=None):\n" " if owner:\n" " if not os.path.exists(filename):\n" " open(filename, 'a').close()\n" " shutil.chown(filename, *owner)\n" " return logging.FileHandler(filename, mode, encoding)\n" "\n" "LOGGING = {\n" " 'version': 1,\n" " 'disable_existing_loggers': False,\n" " 'formatters': {\n" " 'default': {\n" " 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'\n" " },\n" " },\n" " 'handlers': {\n" " 'file':{\n" " # The values below are popped from this dictionary and\n" " # used to create the handler, set the handler's level and\n" " # its formatter.\n" " '()': owned_file_handler,\n" " 'level':'DEBUG',\n" " 'formatter': 'default',\n" " # The values below are passed to the handler creator callable\n" " # as keyword arguments.\n" " 'owner': ['pulse', 'pulse'],\n" " 'filename': 'chowntest.log',\n" " 'mode': 'w',\n" " 'encoding': 'utf-8',\n" " },\n" " },\n" " 'root': {\n" " 'handlers': ['file'],\n" " 'level': 'DEBUG',\n" " },\n" "}\n" "\n" "logging.config.dictConfig(LOGGING)\n" "logger = logging.getLogger('mylogger')\n" "logger.debug('A debug message')" msgstr "" #: ../../howto/logging-cookbook.rst:2681 msgid "To run this, you will probably need to run as ``root``:" msgstr "これを実行するには、 ``root`` 権限で実行する必要があるかもしれません:" #: ../../howto/logging-cookbook.rst:2683 msgid "" "$ sudo python3.3 chowntest.py\n" "$ cat chowntest.log\n" "2013-11-05 09:34:51,128 DEBUG mylogger A debug message\n" "$ ls -l chowntest.log\n" "-rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log" msgstr "" #: ../../howto/logging-cookbook.rst:2691 msgid "" "Note that this example uses Python 3.3 because that's where :func:`shutil." "chown` makes an appearance. This approach should work with any Python " "version that supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. " "With pre-3.3 versions, you would need to implement the actual ownership " "change using e.g. :func:`os.chown`." msgstr "" ":func:`shutil.chown` が追加されたのが Python 3.3 からなので、この例は Python " "3.3 を使っています。このアプローチ自体は :func:`dictConfig` をサポートした全" "ての Python バージョン - Python 2.7, 3.2 以降 - で利用できます。 3.3 以前の" "バージョンでは、オーナーを変更するのに :func:`os.chown` を利用する必要がある" "でしょう。" #: ../../howto/logging-cookbook.rst:2697 msgid "" "In practice, the handler-creating function may be in a utility module " "somewhere in your project. Instead of the line in the configuration::" msgstr "" "実際には、handler を生成する関数はプロジェクト内のどこかにあるユーティリティ" "モジュールに置くことになるでしょう。設定の中で直接関数を参照する代わりに::" #: ../../howto/logging-cookbook.rst:2700 msgid "'()': owned_file_handler," msgstr "" #: ../../howto/logging-cookbook.rst:2702 msgid "you could use e.g.::" msgstr "次のように書くこともできます::" #: ../../howto/logging-cookbook.rst:2704 msgid "'()': 'ext://project.util.owned_file_handler'," msgstr "" #: ../../howto/logging-cookbook.rst:2706 msgid "" "where ``project.util`` can be replaced with the actual name of the package " "where the function resides. In the above working script, using ``'ext://" "__main__.owned_file_handler'`` should work. Here, the actual callable is " "resolved by :func:`dictConfig` from the ``ext://`` specification." msgstr "" "``project.util`` は関数がある実際の場所に置き換えてください。上のスクリプトで" "は ``'ext://__main__.owned_file_handler'`` で動くはずです。 :func:" "`dictConfig` は ``ext://`` から実際の callable を見つけます。" #: ../../howto/logging-cookbook.rst:2711 msgid "" "This example hopefully also points the way to how you could implement other " "types of file change - e.g. setting specific POSIX permission bits - in the " "same way, using :func:`os.chmod`." msgstr "" "この例は他のファイルに対する変更を実装する例にもなっています。例えば :func:" "`os.chmod` を使って、同じ方法で POSIX パーミッションを設定できるでしょう。" #: ../../howto/logging-cookbook.rst:2715 msgid "" "Of course, the approach could also be extended to types of handler other " "than a :class:`~logging.FileHandler` - for example, one of the rotating file " "handlers, or a different type of handler altogether." msgstr "" "もちろん、このアプローチは :class:`~logging.FileHandler` 以外の handler 、" "ローテートする file handler のいずれかやその他の handler にも適用できます。" #: ../../howto/logging-cookbook.rst:2725 msgid "Using particular formatting styles throughout your application" msgstr "固有の書式化スタイルをアプリケーション全体で使う" #: ../../howto/logging-cookbook.rst:2727 msgid "" "In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword " "parameter which, while defaulting to ``%`` for backward compatibility, " "allowed the specification of ``{`` or ``$`` to support the formatting " "approaches supported by :meth:`str.format` and :class:`string.Template`. " "Note that this governs the formatting of logging messages for final output " "to logs, and is completely orthogonal to how an individual logging message " "is constructed." msgstr "" "Python 3.2 では、:class:`~logging.Formatter` クラスが ``style`` という名前の" "オプションのキーワード引数を受け取ります。このデフォルト値は後方互換性を維持" "するために ``%`` となっていますが、 ``{`` か ``$`` を指定することで、:meth:" "`str.format` か :class:`string.Template` でサポートされているのと同じ書式化の" "アプローチを採れます。これは最終的に出力されるログメッセージの書式化に影響を" "与えますが、個々のログメッセージが構築される方法とは完全に直交していることに" "注意してください。" #: ../../howto/logging-cookbook.rst:2734 msgid "" "Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take " "positional parameters for the actual logging message itself, with keyword " "parameters used only for determining options for how to handle the logging " "call (e.g. the ``exc_info`` keyword parameter to indicate that traceback " "information should be logged, or the ``extra`` keyword parameter to indicate " "additional contextual information to be added to the log). So you cannot " "directly make logging calls using :meth:`str.format` or :class:`string." "Template` syntax, because internally the logging package uses %-formatting " "to merge the format string and the variable arguments. There would be no " "changing this while preserving backward compatibility, since all logging " "calls which are out there in existing code will be using %-format strings." msgstr "" "ロギングの呼び出し (:meth:`~Logger.debug`, :meth:`~Logger.info` など) はログ" "メッセージのためには位置引数しか取らず、ロギングの呼び出しを処理する方法を決" "定するためだけにキーワード引数を指定できます (たとえば ``exc_info`` キーワー" "ド引数はトレースバックの情報をログに含めるかどうかを指定し、 ``extra`` キー" "ワード引数はログに付加する追加のコンテキスト情報を指定します)。ロギングパッ" "ケージは内部で %-format を使って書式文字列に可変長引数を埋め込んでいるた" "め、 :meth:`str.format` や :class:`string.Template` の構文を使って直接ロギン" "グの呼び出しを行うことはできません。既存のコードにおける全てのロギングの呼び" "出しは %-format 文字列を使っているため、後方互換性を維持する限りこの部分が変" "更されることはないでしょう。" #: ../../howto/logging-cookbook.rst:2746 msgid "" "There have been suggestions to associate format styles with specific " "loggers, but that approach also runs into backward compatibility problems " "because any existing code could be using a given logger name and using %-" "formatting." msgstr "" "特定のロガーに関連付ける書式スタイルへの提案がなされてきましたが、そのアプ" "ローチは同時に後方互換性の問題にぶち当たります。あらゆる既存のコードはロガー" "の名前を使っているでしょうし、 % 形式書式化を使っているでしょう。" #: ../../howto/logging-cookbook.rst:2750 msgid "" "For logging to work interoperably between any third-party libraries and your " "code, decisions about formatting need to be made at the level of the " "individual logging call. This opens up a couple of ways in which alternative " "formatting styles can be accommodated." msgstr "" "あらゆるサードパーティのライブラリ、あらゆるあなたのコードの間で相互運用可能" "なようにロギングを行うには、書式化についての決定は、個々のログ呼び出しのレベ" "ルで行う必要があります。これは受け容れ可能な代替書式化スタイルに様々な手段の" "可能性を広げます。" #: ../../howto/logging-cookbook.rst:2757 msgid "Using LogRecord factories" msgstr "LogRecord ファクトリを使う" #: ../../howto/logging-cookbook.rst:2759 msgid "" "In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned " "above, the logging package gained the ability to allow users to set their " "own :class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` " "function. You can use this to set your own subclass of :class:`LogRecord`, " "which does the Right Thing by overriding the :meth:`~LogRecord.getMessage` " "method. The base class implementation of this method is where the ``msg % " "args`` formatting happens, and where you can substitute your alternate " "formatting; however, you should be careful to support all formatting styles " "and allow %-formatting as the default, to ensure interoperability with other " "code. Care should also be taken to call ``str(self.msg)``, just as the base " "implementation does." msgstr "" "Python 3.2 において、上述した :class:`~logging.Formatter` の変更とともに、 :" "func:`setLogRecordFactory` 関数を使って :class:`LogRecord` のサブクラスをユー" "ザに指定することを可能にするロギングパッケージの機能拡張がありました。これに" "より、 :meth:`~LogRecord.getMessage` をオーバライドして た だ し い こと" "をする、あなた自身の手による :class:`LogRecord` のサブクラスをセットすること" "が出来ます。このメソッドの実装は基底クラスでは ``msg % args`` 書式化をし、あ" "なたの代替の書式化の置換が出来る場所ですが、他のコードとの相互運用性を保障す" "るために、全ての書式化スタイルをサポートするよう注意深く行うべきであり、ま" "た、%-書式化をデフォルトで認めるべきです。基底クラスの実装がそうしているよう" "に、 ``str(self.msg)`` 呼び出しもしてください。" #: ../../howto/logging-cookbook.rst:2770 msgid "" "Refer to the reference documentation on :func:`setLogRecordFactory` and :" "class:`LogRecord` for more information." msgstr "" "さらに詳しい情報は、リファレンスの :func:`setLogRecordFactory`, :class:" "`LogRecord` を参照してください。" #: ../../howto/logging-cookbook.rst:2775 msgid "Using custom message objects" msgstr "カスタムなメッセージオブジェクトを使う" #: ../../howto/logging-cookbook.rst:2777 msgid "" "There is another, perhaps simpler way that you can use {}- and $- formatting " "to construct your individual log messages. You may recall (from :ref:" "`arbitrary-object-messages`) that when logging you can use an arbitrary " "object as a message format string, and that the logging package will call :" "func:`str` on that object to get the actual format string. Consider the " "following two classes::" msgstr "" "あなた独自のログメッセージを構築するのに {}- および $- 書式化を使えるようにす" "るための、もうひとつの、おそらくもっと簡単な方法があります。ロギングの際に" "は、あなたはメッセージ書式文字列として、任意のオブジェクトを使えることを(:" "ref:`arbitrary-object-messages` より)思い出してみましょう、そしてロギングパッ" "ケージはそのオブジェクトに対して実際の書式文字列を得るために :func:`str` を呼" "び出すことも。以下 2 つのクラスを検討してみましょう::" #: ../../howto/logging-cookbook.rst:2802 msgid "" "Either of these can be used in place of a format string, to allow {}- or $-" "formatting to be used to build the actual \"message\" part which appears in " "the formatted log output in place of “%(message)s” or “{message}” or " "“$message”. If you find it a little unwieldy to use the class names whenever " "you want to log something, you can make it more palatable if you use an " "alias such as ``M`` or ``_`` for the message (or perhaps ``__``, if you are " "using ``_`` for localization)." msgstr "" "どちらのクラスも format 文字列の代わりに利用して、 {} や $ を使って実際のログ" "の “%(message)s”, “{message}”, “$message” で指定された \"message\" 部分を生成" "することができます。これは何かログを取りたいときに常に使うには使いにくいクラ" "ス名ですが、使いやすいようにエイリアスを作れば良いでしょう、 ``M`` であると" "か ``_`` のような(あるいは地域化のために既に ``_`` を使っているのであれば " "``__`` が良いかもしれません)。" #: ../../howto/logging-cookbook.rst:2810 msgid "" "Examples of this approach are given below. Firstly, formatting with :meth:" "`str.format`::" msgstr "" "このアプローチによる例をお見せします。最初は :meth:`str.format` を使って" "フォーマットする例です::" #: ../../howto/logging-cookbook.rst:2813 msgid "" ">>> __ = BraceMessage\n" ">>> print(__('Message with {0} {1}', 2, 'placeholders'))\n" "Message with 2 placeholders\n" ">>> class Point: pass\n" "...\n" ">>> p = Point()\n" ">>> p.x = 0.5\n" ">>> p.y = 0.5\n" ">>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', " "point=p))\n" "Message with coordinates: (0.50, 0.50)" msgstr "" #: ../../howto/logging-cookbook.rst:2824 msgid "Secondly, formatting with :class:`string.Template`::" msgstr "2つめは :class:`string.Template` でフォーマットする例です::" #: ../../howto/logging-cookbook.rst:2826 msgid "" ">>> __ = DollarMessage\n" ">>> print(__('Message with $num $what', num=2, what='placeholders'))\n" "Message with 2 placeholders\n" ">>>" msgstr "" #: ../../howto/logging-cookbook.rst:2831 msgid "" "One thing to note is that you pay no significant performance penalty with " "this approach: the actual formatting happens not when you make the logging " "call, but when (and if) the logged message is actually about to be output to " "a log by a handler. So the only slightly unusual thing which might trip you " "up is that the parentheses go around the format string and the arguments, " "not just the format string. That’s because the __ notation is just syntax " "sugar for a constructor call to one of the :samp:`{XXX}Message` classes " "shown above." msgstr "" "注意点として、この方法には大きなパフォーマンスのペナルティはありません。実際" "のフォーマット操作は logging の呼び出し時ではなくて、メッセージが実際に " "handler によって出力されるときに起こります。(出力されないならフォーマットもさ" "れません) そのため、この方法で注意しないといけないのは、追加の括弧が書式文字" "列だけではなく引数も囲わないといけないことだけです。これは上記のとおり __ " "が :samp:`{XXX}Message` クラスのコンストラクタ呼び出しのシンタックスシュガー" "でしか無いからです。" #: ../../howto/logging-cookbook.rst:2845 msgid "Configuring filters with :func:`dictConfig`" msgstr "filter を :func:`dictConfig` を使ってカスタマイズする" #: ../../howto/logging-cookbook.rst:2847 msgid "" "You *can* configure filters using :func:`~logging.config.dictConfig`, though " "it might not be obvious at first glance how to do it (hence this recipe). " "Since :class:`~logging.Filter` is the only filter class included in the " "standard library, and it is unlikely to cater to many requirements (it's " "only there as a base class), you will typically need to define your own :" "class:`~logging.Filter` subclass with an overridden :meth:`~logging.Filter." "filter` method. To do this, specify the ``()`` key in the configuration " "dictionary for the filter, specifying a callable which will be used to " "create the filter (a class is the most obvious, but you can provide any " "callable which returns a :class:`~logging.Filter` instance). Here is a " "complete example::" msgstr "" ":func:`~logging.config.dictConfig` によってフィルタを設定 *出来ます* が、どう" "やってそれを行うのかが初見では明快とは言えないでしょう(そのためのこのレシピで" "す)。 :class:`~logging.Filter` のみが唯一標準ライブラリに含まれているだけです" "し、それは何の要求にも応えてはくれません(ただの基底クラスですから)ので、典型" "的には :meth:`~logging.Filter.filter` メソッドをオーバライドした :class:" "`~logging.Filter` のサブクラスをあなた自身で定義する必要があります。これをす" "るには、設定辞書内のフィルタ指定部分に、 ``()`` キーでそのフィルタを作るのに" "使われる callable を指定してください(クラスを指定するのが最もわかりやすいです" "が、 :class:`~logging.Filter` インスタンスを返却する callable を提供すること" "でも出来ます)。以下に完全な例を示します::" #: ../../howto/logging-cookbook.rst:2858 msgid "" "import logging\n" "import logging.config\n" "import sys\n" "\n" "class MyFilter(logging.Filter):\n" " def __init__(self, param=None):\n" " self.param = param\n" "\n" " def filter(self, record):\n" " if self.param is None:\n" " allow = True\n" " else:\n" " allow = self.param not in record.msg\n" " if allow:\n" " record.msg = 'changed: ' + record.msg\n" " return allow\n" "\n" "LOGGING = {\n" " 'version': 1,\n" " 'filters': {\n" " 'myfilter': {\n" " '()': MyFilter,\n" " 'param': 'noshow',\n" " }\n" " },\n" " 'handlers': {\n" " 'console': {\n" " 'class': 'logging.StreamHandler',\n" " 'filters': ['myfilter']\n" " }\n" " },\n" " 'root': {\n" " 'level': 'DEBUG',\n" " 'handlers': ['console']\n" " },\n" "}\n" "\n" "if __name__ == '__main__':\n" " logging.config.dictConfig(LOGGING)\n" " logging.debug('hello')\n" " logging.debug('hello - noshow')" msgstr "" #: ../../howto/logging-cookbook.rst:2900 msgid "" "This example shows how you can pass configuration data to the callable which " "constructs the instance, in the form of keyword parameters. When run, the " "above script will print:" msgstr "" "どのようにして設定データとして、そのインスタンスを構築する callable をキー" "ワードパラメータの形で渡すのか、をこの例は教えてくれます。上記スクリプトは実" "行すると、このような出力をします:" #: ../../howto/logging-cookbook.rst:2904 msgid "changed: hello" msgstr "" #: ../../howto/logging-cookbook.rst:2908 msgid "which shows that the filter is working as configured." msgstr "設定した通りに動いていますね。" #: ../../howto/logging-cookbook.rst:2910 msgid "A couple of extra points to note:" msgstr "ほかにもいくつか特筆すべき点があります:" #: ../../howto/logging-cookbook.rst:2912 msgid "" "If you can't refer to the callable directly in the configuration (e.g. if it " "lives in a different module, and you can't import it directly where the " "configuration dictionary is), you can use the form ``ext://...`` as " "described in :ref:`logging-config-dict-externalobj`. For example, you could " "have used the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in " "the above example." msgstr "" "設定内で直接その callable を参照出来ない場合(例えばそれが異なるモジュール内に" "あり、設定辞書のある場所からそれを直接インポート出来ない、など)には、 :ref:" "`logging-config-dict-externalobj` に記述されている ``ext://...`` 形式を使えま" "す。例えば、上記例のように ``MyFilter`` と指定する代わりに、 ``'ext://" "__main__.MyFilter'`` と記述することが出来ます。" #: ../../howto/logging-cookbook.rst:2919 msgid "" "As well as for filters, this technique can also be used to configure custom " "handlers and formatters. See :ref:`logging-config-dict-userdef` for more " "information on how logging supports using user-defined objects in its " "configuration, and see the other cookbook recipe :ref:`custom-handlers` " "above." msgstr "" "フィルタについてとともに、このテクニックは、カスタムハンドラ、カスタムフォー" "マッタに対しても同様に使えます。ロギングが設定において、どのようにユーザ定義" "のオブジェクトをサポートするのかについてのさらなる詳細については、 :ref:" "`logging-config-dict-userdef` と、本クックブックの上の方のレシピ :ref:" "`custom-handlers` を参照してください。" #: ../../howto/logging-cookbook.rst:2928 msgid "Customized exception formatting" msgstr "例外の書式化をカスタマイズする" #: ../../howto/logging-cookbook.rst:2930 msgid "" "There might be times when you want to do customized exception formatting - " "for argument's sake, let's say you want exactly one line per logged event, " "even when exception information is present. You can do this with a custom " "formatter class, as shown in the following example::" msgstr "" "例外の書式化をカスタマイズしたいことがあるでしょう - わかりやすさのために、例" "外情報がある場合でもログイベントごとに一行に収まることを死守したいと望むとし" "ましょう。フォーマッタのクラスをカスタマイズして、このように出来ます::" #: ../../howto/logging-cookbook.rst:2935 msgid "" "import logging\n" "\n" "class OneLineExceptionFormatter(logging.Formatter):\n" " def formatException(self, exc_info):\n" " \"\"\"\n" " Format an exception so that it prints on a single line.\n" " \"\"\"\n" " result = super().formatException(exc_info)\n" " return repr(result) # or format into one line however you want to\n" "\n" " def format(self, record):\n" " s = super().format(record)\n" " if record.exc_text:\n" " s = s.replace('\\n', '') + '|'\n" " return s\n" "\n" "def configure_logging():\n" " fh = logging.FileHandler('output.txt', 'w')\n" " f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',\n" " '%d/%m/%Y %H:%M:%S')\n" " fh.setFormatter(f)\n" " root = logging.getLogger()\n" " root.setLevel(logging.DEBUG)\n" " root.addHandler(fh)\n" "\n" "def main():\n" " configure_logging()\n" " logging.info('Sample message')\n" " try:\n" " x = 1 / 0\n" " except ZeroDivisionError as e:\n" " logging.exception('ZeroDivisionError: %s', e)\n" "\n" "if __name__ == '__main__':\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:2971 msgid "When run, this produces a file with exactly two lines:" msgstr "実行してみましょう。このように正確に2行の出力を生成します:" #: ../../howto/logging-cookbook.rst:2973 msgid "" "28/01/2015 07:21:23|INFO|Sample message|\n" "28/01/2015 07:21:23|ERROR|ZeroDivisionError: division by zero|'Traceback " "(most recent call last):\\n File \"logtest7.py\", line 30, in main\\n x " "= 1 / 0\\nZeroDivisionError: division by zero'|" msgstr "" #: ../../howto/logging-cookbook.rst:2978 msgid "" "While the above treatment is simplistic, it points the way to how exception " "information can be formatted to your liking. The :mod:`traceback` module may " "be helpful for more specialized needs." msgstr "" "これは扱いとしては単純過ぎますが、例外情報をどのようにしてあなた好みの書式化" "出来るかを示しています。さらに特殊なニーズが必要な場合には :mod:`traceback` " "モジュールが有用です。" #: ../../howto/logging-cookbook.rst:2985 msgid "Speaking logging messages" msgstr "ロギングメッセージを喋る" #: ../../howto/logging-cookbook.rst:2987 msgid "" "There might be situations when it is desirable to have logging messages " "rendered in an audible rather than a visible format. This is easy to do if " "you have text-to-speech (TTS) functionality available in your system, even " "if it doesn't have a Python binding. Most TTS systems have a command line " "program you can run, and this can be invoked from a handler using :mod:" "`subprocess`. It's assumed here that TTS command line programs won't expect " "to interact with users or take a long time to complete, and that the " "frequency of logged messages will be not so high as to swamp the user with " "messages, and that it's acceptable to have the messages spoken one at a time " "rather than concurrently, The example implementation below waits for one " "message to be spoken before the next is processed, and this might cause " "other handlers to be kept waiting. Here is a short example showing the " "approach, which assumes that the ``espeak`` TTS package is available::" msgstr "" "ロギングメッセージを目で見る形式ではなく音で聴く形式として出力したい、という" "状況があるかもしれません。これはあなたのシステムで text- to-speech (TTS) 機能" "が利用可能であれば、容易です。それが Python バインディングを持っていなくと" "も、です。ほとんどの TTS システムはあなたが実行出来るコマンドラインプログラム" "を持っていて、このことで、 :mod:`subprocess` を使うことでハンドラが呼び出せま" "す。ここでは、TTS コマンドラインプログラムはユーザとの対話を期待せず、完了に" "は時間がかかり、そしてログメッセージの頻度はユーザをメッセージで圧倒してしま" "うほどには高くはなく、そして並列で喋るよりはメッセージ一つにつき一回喋ること" "が受け容れられる、としておきます。ここでお見せする実装例では、次が処理される" "前に一つのメッセージを喋り終わるまで待ち、結果としてほかのハンドラを待たせる" "ことになります。 ``espeak`` TTS パッケージが手許にあるとして、このアプローチ" "による短い例はこのようなものです::" #: ../../howto/logging-cookbook.rst:3000 msgid "" "import logging\n" "import subprocess\n" "import sys\n" "\n" "class TTSHandler(logging.Handler):\n" " def emit(self, record):\n" " msg = self.format(record)\n" " # Speak slowly in a female English voice\n" " cmd = ['espeak', '-s150', '-ven+f3', msg]\n" " p = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n" " stderr=subprocess.STDOUT)\n" " # wait for the program to finish\n" " p.communicate()\n" "\n" "def configure_logging():\n" " h = TTSHandler()\n" " root = logging.getLogger()\n" " root.addHandler(h)\n" " # the default formatter just returns the message\n" " root.setLevel(logging.DEBUG)\n" "\n" "def main():\n" " logging.info('Hello')\n" " logging.debug('Goodbye')\n" "\n" "if __name__ == '__main__':\n" " configure_logging()\n" " sys.exit(main())" msgstr "" #: ../../howto/logging-cookbook.rst:3029 msgid "" "When run, this script should say \"Hello\" and then \"Goodbye\" in a female " "voice." msgstr "実行すれば、女性の声で \"Hello\" に続き \"Goodbye\" と喋るはずです。" #: ../../howto/logging-cookbook.rst:3031 msgid "" "The above approach can, of course, be adapted to other TTS systems and even " "other systems altogether which can process messages via external programs " "run from a command line." msgstr "" "このアプローチは、もちろんほかの TTS システムにも採用出来ますし、メッセージを" "コマンドライン経由で外部プログラムに渡せるようなものであれば、ほかのシステム" "であっても全く同じです。" #: ../../howto/logging-cookbook.rst:3039 msgid "Buffering logging messages and outputting them conditionally" msgstr "ロギングメッセージをバッファリングし、条件に従って出力する" #: ../../howto/logging-cookbook.rst:3041 msgid "" "There might be situations where you want to log messages in a temporary area " "and only output them if a certain condition occurs. For example, you may " "want to start logging debug events in a function, and if the function " "completes without errors, you don't want to clutter the log with the " "collected debug information, but if there is an error, you want all the " "debug information to be output as well as the error." msgstr "" "メッセージを一次領域に記録し、ある種の特定の状況になった場合にだけ出力した" "い、ということがあるかもしれません。たとえばある関数内でのデバッグのためのロ" "グ出力をしたくても、エラーなしで終了する限りにおいては収集されたデバッグ情報" "による混雑は喰らいたくはなく、エラーがあった場合にだけエラー出力とともにデ" "バッグ情報を見たいのだ、のようなことがあるでしょう。" #: ../../howto/logging-cookbook.rst:3048 msgid "" "Here is an example which shows how you could do this using a decorator for " "your functions where you want logging to behave this way. It makes use of " "the :class:`logging.handlers.MemoryHandler`, which allows buffering of " "logged events until some condition occurs, at which point the buffered " "events are ``flushed`` - passed to another handler (the ``target`` handler) " "for processing. By default, the ``MemoryHandler`` flushed when its buffer " "gets filled up or an event whose level is greater than or equal to a " "specified threshold is seen. You can use this recipe with a more specialised " "subclass of ``MemoryHandler`` if you want custom flushing behavior." msgstr "" "このような振る舞いをするロギングをしたい関数に対して、デコレータを用いてこれ" "を行う例をお見せします。それには :class:`logging.handlers.MemoryHandler` を使" "います。これにより何か条件を満たすまでロギングイベントを溜め込むことが出来、" "条件を満たせば溜め込まれたイベントが ``flushed`` として他のハンドラ " "(``target`` のハンドラ)に渡されます。デフォルトでは、 ``MemoryHandler`` はそ" "のバッファが一杯になるか、指定された閾値のレベル以上のイベントが起こるとフ" "ラッシュされます。何か特別なフラッシュの振る舞いをしたければ、このレシピはさ" "らに特殊化した ``MemoryHandler`` とともに利用出来ます。" #: ../../howto/logging-cookbook.rst:3058 msgid "" "The example script has a simple function, ``foo``, which just cycles through " "all the logging levels, writing to ``sys.stderr`` to say what level it's " "about to log at, and then actually logging a message at that level. You can " "pass a parameter to ``foo`` which, if true, will log at ERROR and CRITICAL " "levels - otherwise, it only logs at DEBUG, INFO and WARNING levels." msgstr "" "スクリプト例では、 ``foo`` という、単に全てのログレベルについて、 ``sys." "stderr`` にもどのレベルを出力したのかについて書き出しながら実際のログ出力も行" "う、という単純な関数を使っています。 ``foo`` に真を与えると ERROR と " "CRITICAL の出力をし、そうでなければ DEBUG, INFO, WARNING だけを出力します。" #: ../../howto/logging-cookbook.rst:3064 msgid "" "The script just arranges to decorate ``foo`` with a decorator which will do " "the conditional logging that's required. The decorator takes a logger as a " "parameter and attaches a memory handler for the duration of the call to the " "decorated function. The decorator can be additionally parameterised using a " "target handler, a level at which flushing should occur, and a capacity for " "the buffer (number of records buffered). These default to a :class:`~logging." "StreamHandler` which writes to ``sys.stderr``, ``logging.ERROR`` and ``100`` " "respectively." msgstr "" "スクリプトが行うことは単に、 ``foo`` を必要とされている特定の条件でのロギング" "を行うようにするデコレータで修飾することだけです。このデコレータはパラメータ" "としてロガーを取り、修飾された関数が呼ばれている間だけメモリハンドラをアタッ" "チします。追加のパラメータとして、ターゲットのハンドラ、フラッシュが発生すべ" "きレベル、バッファの容量(バッファされたレコード数)も受け取れます。これらのデ" "フォルトは順に ``sys.stderr`` へ書き出す :class:`~logging.StreamHandler`, " "``logging.ERROR``, ``100`` です。" #: ../../howto/logging-cookbook.rst:3072 msgid "Here's the script::" msgstr "スクリプトはこれです::" #: ../../howto/logging-cookbook.rst:3074 msgid "" "import logging\n" "from logging.handlers import MemoryHandler\n" "import sys\n" "\n" "logger = logging.getLogger(__name__)\n" "logger.addHandler(logging.NullHandler())\n" "\n" "def log_if_errors(logger, target_handler=None, flush_level=None, " "capacity=None):\n" " if target_handler is None:\n" " target_handler = logging.StreamHandler()\n" " if flush_level is None:\n" " flush_level = logging.ERROR\n" " if capacity is None:\n" " capacity = 100\n" " handler = MemoryHandler(capacity, flushLevel=flush_level, " "target=target_handler)\n" "\n" " def decorator(fn):\n" " def wrapper(*args, **kwargs):\n" " logger.addHandler(handler)\n" " try:\n" " return fn(*args, **kwargs)\n" " except Exception:\n" " logger.exception('call failed')\n" " raise\n" " finally:\n" " super(MemoryHandler, handler).flush()\n" " logger.removeHandler(handler)\n" " return wrapper\n" "\n" " return decorator\n" "\n" "def write_line(s):\n" " sys.stderr.write('%s\\n' % s)\n" "\n" "def foo(fail=False):\n" " write_line('about to log at DEBUG ...')\n" " logger.debug('Actually logged at DEBUG')\n" " write_line('about to log at INFO ...')\n" " logger.info('Actually logged at INFO')\n" " write_line('about to log at WARNING ...')\n" " logger.warning('Actually logged at WARNING')\n" " if fail:\n" " write_line('about to log at ERROR ...')\n" " logger.error('Actually logged at ERROR')\n" " write_line('about to log at CRITICAL ...')\n" " logger.critical('Actually logged at CRITICAL')\n" " return fail\n" "\n" "decorated_foo = log_if_errors(logger)(foo)\n" "\n" "if __name__ == '__main__':\n" " logger.setLevel(logging.DEBUG)\n" " write_line('Calling undecorated foo with False')\n" " assert not foo(False)\n" " write_line('Calling undecorated foo with True')\n" " assert foo(True)\n" " write_line('Calling decorated foo with False')\n" " assert not decorated_foo(False)\n" " write_line('Calling decorated foo with True')\n" " assert decorated_foo(True)" msgstr "" #: ../../howto/logging-cookbook.rst:3135 msgid "When this script is run, the following output should be observed:" msgstr "実行すればこのような出力になるはずです:" #: ../../howto/logging-cookbook.rst:3137 msgid "" "Calling undecorated foo with False\n" "about to log at DEBUG ...\n" "about to log at INFO ...\n" "about to log at WARNING ...\n" "Calling undecorated foo with True\n" "about to log at DEBUG ...\n" "about to log at INFO ...\n" "about to log at WARNING ...\n" "about to log at ERROR ...\n" "about to log at CRITICAL ...\n" "Calling decorated foo with False\n" "about to log at DEBUG ...\n" "about to log at INFO ...\n" "about to log at WARNING ...\n" "Calling decorated foo with True\n" "about to log at DEBUG ...\n" "about to log at INFO ...\n" "about to log at WARNING ...\n" "about to log at ERROR ...\n" "Actually logged at DEBUG\n" "Actually logged at INFO\n" "Actually logged at WARNING\n" "Actually logged at ERROR\n" "about to log at CRITICAL ...\n" "Actually logged at CRITICAL" msgstr "" #: ../../howto/logging-cookbook.rst:3165 msgid "" "As you can see, actual logging output only occurs when an event is logged " "whose severity is ERROR or greater, but in that case, any previous events at " "lower severities are also logged." msgstr "" "見ての通り、実際のログ出力は重要度 ERROR かそれより大きい場合にのみ行っていま" "すが、この場合はそれよりも重要度の低い ERROR よりも前に発生したイベントも出力" "されます。" #: ../../howto/logging-cookbook.rst:3169 msgid "You can of course use the conventional means of decoration::" msgstr "当然のことですが、デコレーションはいつものやり方でどうぞ::" #: ../../howto/logging-cookbook.rst:3171 msgid "" "@log_if_errors(logger)\n" "def foo(fail=False):\n" " ..." msgstr "" #: ../../howto/logging-cookbook.rst:3179 msgid "Sending logging messages to email, with buffering" msgstr "バッファリングしながらロギングメッセージを email で送信する" #: ../../howto/logging-cookbook.rst:3181 msgid "" "To illustrate how you can send log messages via email, so that a set number " "of messages are sent per email, you can subclass :class:`~logging.handlers." "BufferingHandler`. In the following example, which you can adapt to suit " "your specific needs, a simple test harness is provided which allows you to " "run the script with command line arguments specifying what you typically " "need to send things via SMTP. (Run the downloaded script with the ``-h`` " "argument to see the required and optional arguments.)" msgstr "" "ログメッセージをメールで、特に1つのメールにつき複数のログメッセージを、送信す" "る方法を例示するため、 :class:`~logging.handlers.BufferingHandler` を継承しま" "す。以下の例は、必要に応じて改変することもできますが、 SMTP 経由でログを送信" "するのに必要な情報をコマンドライン引数で指定してスクリプトを実行できるように" "簡単なテストハーネスも提供しています (必須の引数およびオプション引数の詳細を" "見るためには、ダウンロードしたスクリプトを ``-h`` 引数をつけて実行してくださ" "い)。" #: ../../howto/logging-cookbook.rst:3189 msgid "" "import logging\n" "import logging.handlers\n" "import smtplib\n" "\n" "class BufferingSMTPHandler(logging.handlers.BufferingHandler):\n" " def __init__(self, mailhost, port, username, password, fromaddr, " "toaddrs,\n" " subject, capacity):\n" " logging.handlers.BufferingHandler.__init__(self, capacity)\n" " self.mailhost = mailhost\n" " self.mailport = port\n" " self.username = username\n" " self.password = password\n" " self.fromaddr = fromaddr\n" " if isinstance(toaddrs, str):\n" " toaddrs = [toaddrs]\n" " self.toaddrs = toaddrs\n" " self.subject = subject\n" " self.setFormatter(logging.Formatter(\"%(asctime)s %(levelname)-5s " "%(message)s\"))\n" "\n" " def flush(self):\n" " if len(self.buffer) > 0:\n" " try:\n" " smtp = smtplib.SMTP(self.mailhost, self.mailport)\n" " smtp.starttls()\n" " smtp.login(self.username, self.password)\n" " msg = \"From: %s\\r\\nTo: %s\\r\\nSubject: %s\\r\\n\\r\\n\" " "% (self.fromaddr, ','.join(self.toaddrs), self.subject)\n" " for record in self.buffer:\n" " s = self.format(record)\n" " msg = msg + s + \"\\r\\n\"\n" " smtp.sendmail(self.fromaddr, self.toaddrs, msg)\n" " smtp.quit()\n" " except Exception:\n" " if logging.raiseExceptions:\n" " raise\n" " self.buffer = []\n" "\n" "if __name__ == '__main__':\n" " import argparse\n" "\n" " ap = argparse.ArgumentParser()\n" " aa = ap.add_argument\n" " aa('host', metavar='HOST', help='SMTP server')\n" " aa('--port', '-p', type=int, default=587, help='SMTP port')\n" " aa('user', metavar='USER', help='SMTP username')\n" " aa('password', metavar='PASSWORD', help='SMTP password')\n" " aa('to', metavar='TO', help='Addressee for emails')\n" " aa('sender', metavar='SENDER', help='Sender email address')\n" " aa('--subject', '-s',\n" " default='Test Logging email from Python logging module (buffering)',\n" " help='Subject of email')\n" " options = ap.parse_args()\n" " logger = logging.getLogger()\n" " logger.setLevel(logging.DEBUG)\n" " h = BufferingSMTPHandler(options.host, options.port, options.user,\n" " options.password, options.sender,\n" " options.to, options.subject, 10)\n" " logger.addHandler(h)\n" " for i in range(102):\n" " logger.info(\"Info index = %d\", i)\n" " h.flush()\n" " h.close()" msgstr "" #: ../../howto/logging-cookbook.rst:3253 msgid "" "If you run this script and your SMTP server is correctly set up, you should " "find that it sends eleven emails to the addressee you specify. The first ten " "emails will each have ten log messages, and the eleventh will have two " "messages. That makes up 102 messages as specified in the script." msgstr "" "SMTP サーバーを正しく設定した上でスクリプトを実行すると、指定したアドレス宛て" "に11通のメールを受け取るでしょう。最初の10通のメールはそれぞれ10個のログメッ" "セージを含み、11通目のメールは2つのログメッセージを含むはずです。これらのログ" "メッセージはスクリプト内で指定された102個のログメッセージから構成されていま" "す。" #: ../../howto/logging-cookbook.rst:3261 msgid "Formatting times using UTC (GMT) via configuration" msgstr "設定によって時刻を UTC(GMT) で書式化する" #: ../../howto/logging-cookbook.rst:3263 msgid "" "Sometimes you want to format times using UTC, which can be done using a " "class such as ``UTCFormatter``, shown below::" msgstr "" "時刻を UTC でフォーマットしたい場合もあるでしょう。以下に示すように、そのよう" "なフォーマット処理は ``UTCFormatter`` のようなクラスを使って行うことができま" "す::" #: ../../howto/logging-cookbook.rst:3266 msgid "" "import logging\n" "import time\n" "\n" "class UTCFormatter(logging.Formatter):\n" " converter = time.gmtime" msgstr "" #: ../../howto/logging-cookbook.rst:3272 msgid "" "and you can then use the ``UTCFormatter`` in your code instead of :class:" "`~logging.Formatter`. If you want to do that via configuration, you can use " "the :func:`~logging.config.dictConfig` API with an approach illustrated by " "the following complete example::" msgstr "" "そしてコード中で ``UTCFormatter`` を :class:`~logging.Formatter` の代わりに使" "えます。これを設定を通して行いたい場合、 :func:`~logging.config.dictConfig` " "API を以下の完全な例で示すようなアプローチで使うことが出来ます::" #: ../../howto/logging-cookbook.rst:3277 msgid "" "import logging\n" "import logging.config\n" "import time\n" "\n" "class UTCFormatter(logging.Formatter):\n" " converter = time.gmtime\n" "\n" "LOGGING = {\n" " 'version': 1,\n" " 'disable_existing_loggers': False,\n" " 'formatters': {\n" " 'utc': {\n" " '()': UTCFormatter,\n" " 'format': '%(asctime)s %(message)s',\n" " },\n" " 'local': {\n" " 'format': '%(asctime)s %(message)s',\n" " }\n" " },\n" " 'handlers': {\n" " 'console1': {\n" " 'class': 'logging.StreamHandler',\n" " 'formatter': 'utc',\n" " },\n" " 'console2': {\n" " 'class': 'logging.StreamHandler',\n" " 'formatter': 'local',\n" " },\n" " },\n" " 'root': {\n" " 'handlers': ['console1', 'console2'],\n" " }\n" "}\n" "\n" "if __name__ == '__main__':\n" " logging.config.dictConfig(LOGGING)\n" " logging.warning('The local time is %s', time.asctime())" msgstr "" #: ../../howto/logging-cookbook.rst:3315 msgid "When this script is run, it should print something like:" msgstr "実行すれば、このような出力になるはずです:" #: ../../howto/logging-cookbook.rst:3317 msgid "" "2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015\n" "2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015" msgstr "" #: ../../howto/logging-cookbook.rst:3322 msgid "" "showing how the time is formatted both as local time and UTC, one for each " "handler." msgstr "" "時刻をローカル時刻と UTC の両方に書式化するのに、それぞれのハンドラにそれぞれ" "フォーマッタを与えています。" #: ../../howto/logging-cookbook.rst:3329 msgid "Using a context manager for selective logging" msgstr "ロギングの選択にコンテキストマネージャを使う" #: ../../howto/logging-cookbook.rst:3331 msgid "" "There are times when it would be useful to temporarily change the logging " "configuration and revert it back after doing something. For this, a context " "manager is the most obvious way of saving and restoring the logging context. " "Here is a simple example of such a context manager, which allows you to " "optionally change the logging level and add a logging handler purely in the " "scope of the context manager::" msgstr "" "一時的にロギングの設定を変えて、作業をした後に設定を戻せると便利なときがあり" "ます。\n" "こういうときの、ロギングコンテキストの保存と復元をする方法ではコンテキストマ" "ネージャを使うのが一番です。\n" "以下にあるのがそのためのコンテキストマネージャの簡単な例で、これを使うと、任" "意にロギングレベルを変更し、コンテキストマネージャのスコープ内で他に影響を及" "ぼさずロギングハンドラを追加できるようになります::" #: ../../howto/logging-cookbook.rst:3338 msgid "" "import logging\n" "import sys\n" "\n" "class LoggingContext:\n" " def __init__(self, logger, level=None, handler=None, close=True):\n" " self.logger = logger\n" " self.level = level\n" " self.handler = handler\n" " self.close = close\n" "\n" " def __enter__(self):\n" " if self.level is not None:\n" " self.old_level = self.logger.level\n" " self.logger.setLevel(self.level)\n" " if self.handler:\n" " self.logger.addHandler(self.handler)\n" "\n" " def __exit__(self, et, ev, tb):\n" " if self.level is not None:\n" " self.logger.setLevel(self.old_level)\n" " if self.handler:\n" " self.logger.removeHandler(self.handler)\n" " if self.handler and self.close:\n" " self.handler.close()\n" " # implicit return of None => don't swallow exceptions" msgstr "" #: ../../howto/logging-cookbook.rst:3364 msgid "" "If you specify a level value, the logger's level is set to that value in the " "scope of the with block covered by the context manager. If you specify a " "handler, it is added to the logger on entry to the block and removed on exit " "from the block. You can also ask the manager to close the handler for you on " "block exit - you could do this if you don't need the handler any more." msgstr "" "レベル値を指定した場合、コンテキストマネージャがカバーする with ブロックのス" "コープ内でロガーのレベルがその値に設定されます。\n" "ハンドラーを指定した場合、ブロックに入るときにロガーに追加され、ブロックから" "抜けるときに取り除かれます。\n" "ブロックを抜けるときに、自分で追加したハンドラをクローズするようコンテキスト" "マネージャに指示することもできます - そのハンドラがそれ以降必要無いのであれば" "クローズしてしまって構いません。" #: ../../howto/logging-cookbook.rst:3370 msgid "" "To illustrate how it works, we can add the following block of code to the " "above::" msgstr "" "どのように動作するのかを示すためには、次のコード群を上のコードに付け加えると" "よいです::" #: ../../howto/logging-cookbook.rst:3373 msgid "" "if __name__ == '__main__':\n" " logger = logging.getLogger('foo')\n" " logger.addHandler(logging.StreamHandler())\n" " logger.setLevel(logging.INFO)\n" " logger.info('1. This should appear just once on stderr.')\n" " logger.debug('2. This should not appear.')\n" " with LoggingContext(logger, level=logging.DEBUG):\n" " logger.debug('3. This should appear once on stderr.')\n" " logger.debug('4. This should not appear.')\n" " h = logging.StreamHandler(sys.stdout)\n" " with LoggingContext(logger, level=logging.DEBUG, handler=h, " "close=True):\n" " logger.debug('5. This should appear twice - once on stderr and once " "on stdout.')\n" " logger.info('6. This should appear just once on stderr.')\n" " logger.debug('7. This should not appear.')" msgstr "" #: ../../howto/logging-cookbook.rst:3388 msgid "" "We initially set the logger's level to ``INFO``, so message #1 appears and " "message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the " "following ``with`` block, and so message #3 appears. After the block exits, " "the logger's level is restored to ``INFO`` and so message #4 doesn't appear. " "In the next ``with`` block, we set the level to ``DEBUG`` again but also add " "a handler writing to ``sys.stdout``. Thus, message #5 appears twice on the " "console (once via ``stderr`` and once via ``stdout``). After the ``with`` " "statement's completion, the status is as it was before so message #6 appears " "(like message #1) whereas message #7 doesn't (just like message #2)." msgstr "" "最初はロガーのレベルを ``INFO`` に設定しているので、メッセージ #1 は現れ、" "メッセージ #2 は現れません。\n" "次に、その後の ``with`` ブロック内で一時的にレベルを ``DEBUG`` に変更したた" "め、メッセージ #3 が現れます。\n" "そのブロックを抜けた後、ロガーのレベルは ``INFO`` に復元され、メッセージ #4 " "は現れません。\n" "次の ``with`` ブロック内では、再度レベルを ``DEBUG`` に設定し、 ``sys." "stdout`` に書き出すハンドラを追加します。\n" "そのおかげでメッセージ #5 が 2 回 (1回は ``stderr`` を通して、もう1回は " "``stdout`` を通して) コンソールに出力されます。\n" "``with`` 文が完了すると、前の状態になるので (メッセージ #1 のように) メッセー" "ジ #6 が現れ、(まさにメッセージ #2 のように) メッセージ #7 は現れません。" #: ../../howto/logging-cookbook.rst:3398 msgid "If we run the resulting script, the result is as follows:" msgstr "出来上がったスクリプトを実行すると、結果は次のようになります::" #: ../../howto/logging-cookbook.rst:3400 msgid "" "$ python logctx.py\n" "1. This should appear just once on stderr.\n" "3. This should appear once on stderr.\n" "5. This should appear twice - once on stderr and once on stdout.\n" "5. This should appear twice - once on stderr and once on stdout.\n" "6. This should appear just once on stderr." msgstr "" #: ../../howto/logging-cookbook.rst:3409 msgid "" "If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the " "following, which is the only message written to ``stdout``:" msgstr "" "``stderr`` を ``/dev/null`` へパイプした状態でもう一度実行すると、次のように" "なり、これは ``stdout`` の方に書かれたメッセージだけが現れています:" #: ../../howto/logging-cookbook.rst:3412 msgid "" "$ python logctx.py 2>/dev/null\n" "5. This should appear twice - once on stderr and once on stdout." msgstr "" #: ../../howto/logging-cookbook.rst:3417 msgid "Once again, but piping ``stdout`` to ``/dev/null``, we get:" msgstr "" "``stdout`` を ``/dev/null`` へパイプした状態でさらにもう一度実行すると、こう" "なります:" #: ../../howto/logging-cookbook.rst:3419 msgid "" "$ python logctx.py >/dev/null\n" "1. This should appear just once on stderr.\n" "3. This should appear once on stderr.\n" "5. This should appear twice - once on stderr and once on stdout.\n" "6. This should appear just once on stderr." msgstr "" #: ../../howto/logging-cookbook.rst:3427 msgid "" "In this case, the message #5 printed to ``stdout`` doesn't appear, as " "expected." msgstr "" "この場合では、 ``stdout`` の方に出力されたメッセージ #5 は予想通り現れませ" "ん。" #: ../../howto/logging-cookbook.rst:3429 msgid "" "Of course, the approach described here can be generalised, for example to " "attach logging filters temporarily. Note that the above code works in Python " "2 as well as Python 3." msgstr "" "もちろんここで説明した手法は、例えば一時的にロギングフィルターを取り付けたり" "するのに一般化できます。\n" "上のコードは Python 2 だけでなく Python 3 でも動くことに注意してください。" #: ../../howto/logging-cookbook.rst:3437 msgid "A CLI application starter template" msgstr "CLIアプリケーションスターターテンプレート" #: ../../howto/logging-cookbook.rst:3439 msgid "Here's an example which shows how you can:" msgstr "ここのサンプルでは次のことを説明します:" #: ../../howto/logging-cookbook.rst:3441 msgid "Use a logging level based on command-line arguments" msgstr "コマンドライン引数に応じてログレベルを使用する" #: ../../howto/logging-cookbook.rst:3442 msgid "" "Dispatch to multiple subcommands in separate files, all logging at the same " "level in a consistent way" msgstr "" "複数のファイルに分割されたサブコマンドにディスパッチする。すべて一貫して同じ" "レベルでログ出力を行う" #: ../../howto/logging-cookbook.rst:3444 msgid "Make use of simple, minimal configuration" msgstr "シンプルで最小限の設定で行えるようにする" #: ../../howto/logging-cookbook.rst:3446 msgid "" "Suppose we have a command-line application whose job is to stop, start or " "restart some services. This could be organised for the purposes of " "illustration as a file ``app.py`` that is the main script for the " "application, with individual commands implemented in ``start.py``, ``stop." "py`` and ``restart.py``. Suppose further that we want to control the " "verbosity of the application via a command-line argument, defaulting to " "``logging.INFO``. Here's one way that ``app.py`` could be written::" msgstr "" "サービスを停止したり、開始したり、再起動する役割を持ったコマンドラインアプリ" "ケーションがあるとします。説明のために、アプリケーションのメインスクリプトが " "``app.py`` 、個々のコマンドが ``start.py`` 、 ``stop.py`` 、 ``restart.py`` " "に実装されているものとします。デフォルトは ``logging.INFO`` ですが、コマンド" "ライン引数を使ってアプリケーションのログの冗長性を制御したいとします。 ``app." "py`` は次のコードのようになるでしょう::" #: ../../howto/logging-cookbook.rst:3454 msgid "" "import argparse\n" "import importlib\n" "import logging\n" "import os\n" "import sys\n" "\n" "def main(args=None):\n" " scriptname = os.path.basename(__file__)\n" " parser = argparse.ArgumentParser(scriptname)\n" " levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')\n" " parser.add_argument('--log-level', default='INFO', choices=levels)\n" " subparsers = parser.add_subparsers(dest='command',\n" " help='Available commands:')\n" " start_cmd = subparsers.add_parser('start', help='Start a service')\n" " start_cmd.add_argument('name', metavar='NAME',\n" " help='Name of service to start')\n" " stop_cmd = subparsers.add_parser('stop',\n" " help='Stop one or more services')\n" " stop_cmd.add_argument('names', metavar='NAME', nargs='+',\n" " help='Name of service to stop')\n" " restart_cmd = subparsers.add_parser('restart',\n" " help='Restart one or more " "services')\n" " restart_cmd.add_argument('names', metavar='NAME', nargs='+',\n" " help='Name of service to restart')\n" " options = parser.parse_args()\n" " # the code to dispatch commands could all be in this file. For the " "purposes\n" " # of illustration only, we implement each command in a separate module.\n" " try:\n" " mod = importlib.import_module(options.command)\n" " cmd = getattr(mod, 'command')\n" " except (ImportError, AttributeError):\n" " print('Unable to find the code for command \\'%s\\'' % options." "command)\n" " return 1\n" " # Could get fancy here and load configuration from file or dictionary\n" " logging.basicConfig(level=options.log_level,\n" " format='%(levelname)s %(name)s %(message)s')\n" " cmd(options)\n" "\n" "if __name__ == '__main__':\n" " sys.exit(main())" msgstr "" #: ../../howto/logging-cookbook.rst:3495 msgid "" "And the ``start``, ``stop`` and ``restart`` commands can be implemented in " "separate modules, like so for starting::" msgstr "" "``start`` 、 ``stop`` 、 ``restart`` コマンドは個別のモジュールとして実装され" "ます。次は起動コマンドのソースです::" #: ../../howto/logging-cookbook.rst:3498 msgid "" "# start.py\n" "import logging\n" "\n" "logger = logging.getLogger(__name__)\n" "\n" "def command(options):\n" " logger.debug('About to start %s', options.name)\n" " # actually do the command processing here ...\n" " logger.info('Started the \\'%s\\' service.', options.name)" msgstr "" #: ../../howto/logging-cookbook.rst:3508 msgid "and thus for stopping::" msgstr "停止コマンドのソースは次の通りです::" #: ../../howto/logging-cookbook.rst:3510 msgid "" "# stop.py\n" "import logging\n" "\n" "logger = logging.getLogger(__name__)\n" "\n" "def command(options):\n" " n = len(options.names)\n" " if n == 1:\n" " plural = ''\n" " services = '\\'%s\\'' % options.names[0]\n" " else:\n" " plural = 's'\n" " services = ', '.join('\\'%s\\'' % name for name in options.names)\n" " i = services.rfind(', ')\n" " services = services[:i] + ' and ' + services[i + 2:]\n" " logger.debug('About to stop %s', services)\n" " # actually do the command processing here ...\n" " logger.info('Stopped the %s service%s.', services, plural)" msgstr "" #: ../../howto/logging-cookbook.rst:3529 msgid "and similarly for restarting::" msgstr "同様に、再起動のコマンドは次の通りです::" #: ../../howto/logging-cookbook.rst:3531 msgid "" "# restart.py\n" "import logging\n" "\n" "logger = logging.getLogger(__name__)\n" "\n" "def command(options):\n" " n = len(options.names)\n" " if n == 1:\n" " plural = ''\n" " services = '\\'%s\\'' % options.names[0]\n" " else:\n" " plural = 's'\n" " services = ', '.join('\\'%s\\'' % name for name in options.names)\n" " i = services.rfind(', ')\n" " services = services[:i] + ' and ' + services[i + 2:]\n" " logger.debug('About to restart %s', services)\n" " # actually do the command processing here ...\n" " logger.info('Restarted the %s service%s.', services, plural)" msgstr "" #: ../../howto/logging-cookbook.rst:3550 msgid "" "If we run this application with the default log level, we get output like " "this:" msgstr "" "このアプリケーションをデフォルトのログレベルで実行すると、次のような出力が得" "られます:" #: ../../howto/logging-cookbook.rst:3552 msgid "" "$ python app.py start foo\n" "INFO start Started the 'foo' service.\n" "\n" "$ python app.py stop foo bar\n" "INFO stop Stopped the 'foo' and 'bar' services.\n" "\n" "$ python app.py restart foo bar baz\n" "INFO restart Restarted the 'foo', 'bar' and 'baz' services." msgstr "" #: ../../howto/logging-cookbook.rst:3563 msgid "" "The first word is the logging level, and the second word is the module or " "package name of the place where the event was logged." msgstr "" "最初のワードはログレベルで、次のワードはイベントのログ出力が行われたモジュー" "ルまたはパッケージ名です。" #: ../../howto/logging-cookbook.rst:3566 msgid "" "If we change the logging level, then we can change the information sent to " "the log. For example, if we want more information:" msgstr "" "ログレベルを変更し、ログに出力する情報を変更できるようにしましょう。もし、よ" "り詳細な情報が必要だとしましょう:" #: ../../howto/logging-cookbook.rst:3569 msgid "" "$ python app.py --log-level DEBUG start foo\n" "DEBUG start About to start foo\n" "INFO start Started the 'foo' service.\n" "\n" "$ python app.py --log-level DEBUG stop foo bar\n" "DEBUG stop About to stop 'foo' and 'bar'\n" "INFO stop Stopped the 'foo' and 'bar' services.\n" "\n" "$ python app.py --log-level DEBUG restart foo bar baz\n" "DEBUG restart About to restart 'foo', 'bar' and 'baz'\n" "INFO restart Restarted the 'foo', 'bar' and 'baz' services." msgstr "" #: ../../howto/logging-cookbook.rst:3583 msgid "And if we want less:" msgstr "あるいは情報を減らしたい場合もあるでしょう:" #: ../../howto/logging-cookbook.rst:3585 msgid "" "$ python app.py --log-level WARNING start foo\n" "$ python app.py --log-level WARNING stop foo bar\n" "$ python app.py --log-level WARNING restart foo bar baz" msgstr "" #: ../../howto/logging-cookbook.rst:3591 msgid "" "In this case, the commands don't print anything to the console, since " "nothing at ``WARNING`` level or above is logged by them." msgstr "この場合、コマンドはコンソールに何も出力しなくなります。" #: ../../howto/logging-cookbook.rst:3597 msgid "A Qt GUI for logging" msgstr "Qt GUIのログ出力" #: ../../howto/logging-cookbook.rst:3599 msgid "" "A question that comes up from time to time is about how to log to a GUI " "application. The `Qt `_ framework is a popular cross-" "platform UI framework with Python bindings using :pypi:`PySide2` or :pypi:" "`PyQt5` libraries." msgstr "" #: ../../howto/logging-cookbook.rst:3604 msgid "" "The following example shows how to log to a Qt GUI. This introduces a simple " "``QtHandler`` class which takes a callable, which should be a slot in the " "main thread that does GUI updates. A worker thread is also created to show " "how you can log to the GUI from both the UI itself (via a button for manual " "logging) as well as a worker thread doing work in the background (here, just " "logging messages at random levels with random short delays in between)." msgstr "" "次のサンプルはQt GUIでログ出力を行うサンプルです。ここではシンプルな " "``QtHandler`` クラスを作成しています。これは呼び出し可能オブジェクトを受け取" "ります。これはGUI更新を行うメインスレッドの中で利用されるスロットです。ワー" "カースレッドも作成し、UI自身からボタンを使ってログを出力したり、バックグラウ" "ンドのタスクを行うワーカースレッドからログ出力を行います(ここではランダムな" "期間にランダムなレベルでメッセージを出しています)。" #: ../../howto/logging-cookbook.rst:3611 msgid "" "The worker thread is implemented using Qt's ``QThread`` class rather than " "the :mod:`threading` module, as there are circumstances where one has to use " "``QThread``, which offers better integration with other ``Qt`` components." msgstr "" "ワーカースレッドは :mod:`threading` モジュールではなく、Qtの ``QThread`` クラ" "スを使っています。これは他の ``Qt`` コンポーネントとうまく統合できるように、 " "``QThread`` を使う必要があるからです。" #: ../../howto/logging-cookbook.rst:3615 msgid "" "The code should work with recent releases of any of ``PySide6``, ``PyQt6``, " "``PySide2`` or ``PyQt5``. You should be able to adapt the approach to " "earlier versions of Qt. Please refer to the comments in the code snippet for " "more detailed information." msgstr "" #: ../../howto/logging-cookbook.rst:3620 msgid "" "import datetime\n" "import logging\n" "import random\n" "import sys\n" "import time\n" "\n" "# Deal with minor differences between different Qt packages\n" "try:\n" " from PySide6 import QtCore, QtGui, QtWidgets\n" " Signal = QtCore.Signal\n" " Slot = QtCore.Slot\n" "except ImportError:\n" " try:\n" " from PyQt6 import QtCore, QtGui, QtWidgets\n" " Signal = QtCore.pyqtSignal\n" " Slot = QtCore.pyqtSlot\n" " except ImportError:\n" " try:\n" " from PySide2 import QtCore, QtGui, QtWidgets\n" " Signal = QtCore.Signal\n" " Slot = QtCore.Slot\n" " except ImportError:\n" " from PyQt5 import QtCore, QtGui, QtWidgets\n" " Signal = QtCore.pyqtSignal\n" " Slot = QtCore.pyqtSlot\n" "\n" "logger = logging.getLogger(__name__)\n" "\n" "\n" "#\n" "# Signals need to be contained in a QObject or subclass in order to be " "correctly\n" "# initialized.\n" "#\n" "class Signaller(QtCore.QObject):\n" " signal = Signal(str, logging.LogRecord)\n" "\n" "#\n" "# Output to a Qt GUI is only supposed to happen on the main thread. So, " "this\n" "# handler is designed to take a slot function which is set up to run in the " "main\n" "# thread. In this example, the function takes a string argument which is a\n" "# formatted log message, and the log record which generated it. The " "formatted\n" "# string is just a convenience - you could format a string for output any " "way\n" "# you like in the slot function itself.\n" "#\n" "# You specify the slot function to do whatever GUI updates you want. The " "handler\n" "# doesn't know or care about specific UI elements.\n" "#\n" "class QtHandler(logging.Handler):\n" " def __init__(self, slotfunc, *args, **kwargs):\n" " super().__init__(*args, **kwargs)\n" " self.signaller = Signaller()\n" " self.signaller.signal.connect(slotfunc)\n" "\n" " def emit(self, record):\n" " s = self.format(record)\n" " self.signaller.signal.emit(s, record)\n" "\n" "#\n" "# This example uses QThreads, which means that the threads at the Python " "level\n" "# are named something like \"Dummy-1\". The function below gets the Qt name " "of the\n" "# current thread.\n" "#\n" "def ctname():\n" " return QtCore.QThread.currentThread().objectName()\n" "\n" "\n" "#\n" "# Used to generate random levels for logging.\n" "#\n" "LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" " logging.CRITICAL)\n" "\n" "#\n" "# This worker class represents work that is done in a thread separate to " "the\n" "# main thread. The way the thread is kicked off to do work is via a button " "press\n" "# that connects to a slot in the worker.\n" "#\n" "# Because the default threadName value in the LogRecord isn't much use, we " "add\n" "# a qThreadName which contains the QThread name as computed above, and pass " "that\n" "# value in an \"extra\" dictionary which is used to update the LogRecord " "with the\n" "# QThread name.\n" "#\n" "# This example worker just outputs messages sequentially, interspersed with\n" "# random delays of the order of a few seconds.\n" "#\n" "class Worker(QtCore.QObject):\n" " @Slot()\n" " def start(self):\n" " extra = {'qThreadName': ctname() }\n" " logger.debug('Started work', extra=extra)\n" " i = 1\n" " # Let the thread run until interrupted. This allows reasonably " "clean\n" " # thread termination.\n" " while not QtCore.QThread.currentThread().isInterruptionRequested():\n" " delay = 0.5 + random.random() * 2\n" " time.sleep(delay)\n" " try:\n" " if random.random() < 0.1:\n" " raise ValueError('Exception raised: %d' % i)\n" " else:\n" " level = random.choice(LEVELS)\n" " logger.log(level, 'Message after delay of %3.1f: %d', " "delay, i, extra=extra)\n" " except ValueError as e:\n" " logger.exception('Failed: %s', e, extra=extra)\n" " i += 1\n" "\n" "#\n" "# Implement a simple UI for this cookbook example. This contains:\n" "#\n" "# * A read-only text edit window which holds formatted log messages\n" "# * A button to start work and log stuff in a separate thread\n" "# * A button to log something from the main thread\n" "# * A button to clear the log window\n" "#\n" "class Window(QtWidgets.QWidget):\n" "\n" " COLORS = {\n" " logging.DEBUG: 'black',\n" " logging.INFO: 'blue',\n" " logging.WARNING: 'orange',\n" " logging.ERROR: 'red',\n" " logging.CRITICAL: 'purple',\n" " }\n" "\n" " def __init__(self, app):\n" " super().__init__()\n" " self.app = app\n" " self.textedit = te = QtWidgets.QPlainTextEdit(self)\n" " # Set whatever the default monospace font is for the platform\n" " f = QtGui.QFont('nosuchfont')\n" " if hasattr(f, 'Monospace'):\n" " f.setStyleHint(f.Monospace)\n" " else:\n" " f.setStyleHint(f.StyleHint.Monospace) # for Qt6\n" " te.setFont(f)\n" " te.setReadOnly(True)\n" " PB = QtWidgets.QPushButton\n" " self.work_button = PB('Start background work', self)\n" " self.log_button = PB('Log a message at a random level', self)\n" " self.clear_button = PB('Clear log window', self)\n" " self.handler = h = QtHandler(self.update_status)\n" " # Remember to use qThreadName rather than threadName in the format " "string.\n" " fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s'\n" " formatter = logging.Formatter(fs)\n" " h.setFormatter(formatter)\n" " logger.addHandler(h)\n" " # Set up to terminate the QThread when we exit\n" " app.aboutToQuit.connect(self.force_quit)\n" "\n" " # Lay out all the widgets\n" " layout = QtWidgets.QVBoxLayout(self)\n" " layout.addWidget(te)\n" " layout.addWidget(self.work_button)\n" " layout.addWidget(self.log_button)\n" " layout.addWidget(self.clear_button)\n" " self.setFixedSize(900, 400)\n" "\n" " # Connect the non-worker slots and signals\n" " self.log_button.clicked.connect(self.manual_update)\n" " self.clear_button.clicked.connect(self.clear_display)\n" "\n" " # Start a new worker thread and connect the slots for the worker\n" " self.start_thread()\n" " self.work_button.clicked.connect(self.worker.start)\n" " # Once started, the button should be disabled\n" " self.work_button.clicked.connect(lambda : self.work_button." "setEnabled(False))\n" "\n" " def start_thread(self):\n" " self.worker = Worker()\n" " self.worker_thread = QtCore.QThread()\n" " self.worker.setObjectName('Worker')\n" " self.worker_thread.setObjectName('WorkerThread') # for qThreadName\n" " self.worker.moveToThread(self.worker_thread)\n" " # This will start an event loop in the worker thread\n" " self.worker_thread.start()\n" "\n" " def kill_thread(self):\n" " # Just tell the worker to stop, then tell it to quit and wait for " "that\n" " # to happen\n" " self.worker_thread.requestInterruption()\n" " if self.worker_thread.isRunning():\n" " self.worker_thread.quit()\n" " self.worker_thread.wait()\n" " else:\n" " print('worker has already exited.')\n" "\n" " def force_quit(self):\n" " # For use when the window is closed\n" " if self.worker_thread.isRunning():\n" " self.kill_thread()\n" "\n" " # The functions below update the UI and run in the main thread because\n" " # that's where the slots are set up\n" "\n" " @Slot(str, logging.LogRecord)\n" " def update_status(self, status, record):\n" " color = self.COLORS.get(record.levelno, 'black')\n" " s = '
%s
' % (color, status)\n" " self.textedit.appendHtml(s)\n" "\n" " @Slot()\n" " def manual_update(self):\n" " # This function uses the formatted message passed in, but also uses\n" " # information from the record to format the message in an " "appropriate\n" " # color according to its severity (level).\n" " level = random.choice(LEVELS)\n" " extra = {'qThreadName': ctname() }\n" " logger.log(level, 'Manually logged!', extra=extra)\n" "\n" " @Slot()\n" " def clear_display(self):\n" " self.textedit.clear()\n" "\n" "\n" "def main():\n" " QtCore.QThread.currentThread().setObjectName('MainThread')\n" " logging.getLogger().setLevel(logging.DEBUG)\n" " app = QtWidgets.QApplication(sys.argv)\n" " example = Window(app)\n" " example.show()\n" " if hasattr(app, 'exec'):\n" " rc = app.exec()\n" " else:\n" " rc = app.exec_()\n" " sys.exit(rc)\n" "\n" "if __name__=='__main__':\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:3852 msgid "Logging to syslog with RFC5424 support" msgstr "RFC5424 をサポートする syslog へのロギング" #: ../../howto/logging-cookbook.rst:3854 msgid "" "Although :rfc:`5424` dates from 2009, most syslog servers are configured by " "default to use the older :rfc:`3164`, which hails from 2001. When " "``logging`` was added to Python in 2003, it supported the earlier (and only " "existing) protocol at the time. Since RFC5424 came out, as there has not " "been widespread deployment of it in syslog servers, the :class:`~logging." "handlers.SysLogHandler` functionality has not been updated." msgstr "" ":rfc:`5424` は 2009 年から始まっていますが、ほとんどの syslog サーバーはデ" "フォルトで、 2001 年から使われている古い :rfc:`3164` を使って構成されていま" "す。2003年に ``logging`` モジュールが Python に追加されたとき、モジュールは古" "い (そして当時唯一存在した) プロトコルをサポートしていました。 RFC5424 は、そ" "れが登場して以来、 syslog サーバーにおいて広く使われることがなかったため" "に、 :class:`~logging.handlers.SysLogHandler` の機能は更新されてきませんでし" "た。" #: ../../howto/logging-cookbook.rst:3861 msgid "" "RFC 5424 contains some useful features such as support for structured data, " "and if you need to be able to log to a syslog server with support for it, " "you can do so with a subclassed handler which looks something like this::" msgstr "" "RFC 5424 は構造化データのサポートなど、いくつかの有用な機能を持っています。そ" "の機能をサポートする syslog サーバーへのロギングを可能にする必要がある場合、" "以下のような派生ハンドラクラスを使うことで実現することができます::" #: ../../howto/logging-cookbook.rst:3865 msgid "" "import datetime\n" "import logging.handlers\n" "import re\n" "import socket\n" "import time\n" "\n" "class SysLogHandler5424(logging.handlers.SysLogHandler):\n" "\n" " tz_offset = re.compile(r'([+-]\\d{2})(\\d{2})$')\n" " escaped = re.compile(r'([\\]\"\\\\])')\n" "\n" " def __init__(self, *args, **kwargs):\n" " self.msgid = kwargs.pop('msgid', None)\n" " self.appname = kwargs.pop('appname', None)\n" " super().__init__(*args, **kwargs)\n" "\n" " def format(self, record):\n" " version = 1\n" " asctime = datetime.datetime.fromtimestamp(record.created)." "isoformat()\n" " m = self.tz_offset.match(time.strftime('%z'))\n" " has_offset = False\n" " if m and time.timezone:\n" " hrs, mins = m.groups()\n" " if int(hrs) or int(mins):\n" " has_offset = True\n" " if not has_offset:\n" " asctime += 'Z'\n" " else:\n" " asctime += f'{hrs}:{mins}'\n" " try:\n" " hostname = socket.gethostname()\n" " except Exception:\n" " hostname = '-'\n" " appname = self.appname or '-'\n" " procid = record.process\n" " msgid = '-'\n" " msg = super().format(record)\n" " sdata = '-'\n" " if hasattr(record, 'structured_data'):\n" " sd = record.structured_data\n" " # This should be a dict where the keys are SD-ID and the value " "is a\n" " # dict mapping PARAM-NAME to PARAM-VALUE (refer to the RFC for " "what these\n" " # mean)\n" " # There's no error checking here - it's purely for illustration, " "and you\n" " # can adapt this code for use in production environments\n" " parts = []\n" "\n" " def replacer(m):\n" " g = m.groups()\n" " return '\\\\' + g[0]\n" "\n" " for sdid, dv in sd.items():\n" " part = f'[{sdid}'\n" " for k, v in dv.items():\n" " s = str(v)\n" " s = self.escaped.sub(replacer, s)\n" " part += f' {k}=\"{s}\"'\n" " part += ']'\n" " parts.append(part)\n" " sdata = ''.join(parts)\n" " return f'{version} {asctime} {hostname} {appname} {procid} {msgid} " "{sdata} {msg}'" msgstr "" #: ../../howto/logging-cookbook.rst:3927 msgid "" "You'll need to be familiar with RFC 5424 to fully understand the above code, " "and it may be that you have slightly different needs (e.g. for how you pass " "structural data to the log). Nevertheless, the above should be adaptable to " "your speciric needs. With the above handler, you'd pass structured data " "using something like this::" msgstr "" "上記のコードを完全に理解するには RFC 5424 を熟知する必要があります。また、上" "記の例とはやや異なる要求を持つこともあるでしょう (たとえば構造化データをログ" "に渡す方法について)。にもかかわらず、上記のコードは特有の要求に対する順応性が" "あります。上記のハンドラにより、構造化データは以下のように渡すことができるで" "しょう::" #: ../../howto/logging-cookbook.rst:3932 msgid "" "sd = {\n" " 'foo@12345': {'bar': 'baz', 'baz': 'bozz', 'fizz': r'buzz'},\n" " 'foo@54321': {'rab': 'baz', 'zab': 'bozz', 'zzif': r'buzz'}\n" "}\n" "extra = {'structured_data': sd}\n" "i = 1\n" "logger.debug('Message %d', i, extra=extra)" msgstr "" #: ../../howto/logging-cookbook.rst:3941 msgid "How to treat a logger like an output stream" msgstr "ロガーを出力ストリームのように取り扱う方法" #: ../../howto/logging-cookbook.rst:3943 msgid "" "Sometimes, you need to interface to a third-party API which expects a file-" "like object to write to, but you want to direct the API's output to a " "logger. You can do this using a class which wraps a logger with a file-like " "API. Here's a short script illustrating such a class:" msgstr "" "書き込み先として file-like オブジェクトを期待するサードパーティの API に接続" "する必要がある一方で、その API の出力を直接ロガーに送りたいということがときど" "きあります。これは file-like な API でロガーをラップするクラスを使うことで実" "現できます。以下はそのようなクラスを例解する短いスクリプトです:" #: ../../howto/logging-cookbook.rst:3948 msgid "" "import logging\n" "\n" "class LoggerWriter:\n" " def __init__(self, logger, level):\n" " self.logger = logger\n" " self.level = level\n" "\n" " def write(self, message):\n" " if message != '\\n': # avoid printing bare newlines, if you like\n" " self.logger.log(self.level, message)\n" "\n" " def flush(self):\n" " # doesn't actually do anything, but might be expected of a file-" "like\n" " # object - so optional depending on your situation\n" " pass\n" "\n" " def close(self):\n" " # doesn't actually do anything, but might be expected of a file-" "like\n" " # object - so optional depending on your situation. You might want\n" " # to set a flag so that later calls to write raise an exception\n" " pass\n" "\n" "def main():\n" " logging.basicConfig(level=logging.DEBUG)\n" " logger = logging.getLogger('demo')\n" " info_fp = LoggerWriter(logger, logging.INFO)\n" " debug_fp = LoggerWriter(logger, logging.DEBUG)\n" " print('An INFO message', file=info_fp)\n" " print('A DEBUG message', file=debug_fp)\n" "\n" "if __name__ == \"__main__\":\n" " main()" msgstr "" #: ../../howto/logging-cookbook.rst:3983 msgid "When this script is run, it prints" msgstr "このスクリプトを実行すると、次のように出力されます。" #: ../../howto/logging-cookbook.rst:3985 msgid "" "INFO:demo:An INFO message\n" "DEBUG:demo:A DEBUG message" msgstr "" #: ../../howto/logging-cookbook.rst:3990 msgid "" "You could also use ``LoggerWriter`` to redirect ``sys.stdout`` and ``sys." "stderr`` by doing something like this:" msgstr "" "また、 ``sys.stdout`` や ``sys.stderr`` をリダイレクトするには " "``LoggerWriter`` を使って以下のようにします:" #: ../../howto/logging-cookbook.rst:3993 msgid "" "import sys\n" "\n" "sys.stdout = LoggerWriter(logger, logging.INFO)\n" "sys.stderr = LoggerWriter(logger, logging.WARNING)" msgstr "" #: ../../howto/logging-cookbook.rst:4000 msgid "" "You should do this *after* configuring logging for your needs. In the above " "example, the :func:`~logging.basicConfig` call does this (using the ``sys." "stderr`` value *before* it is overwritten by a ``LoggerWriter`` instance). " "Then, you'd get this kind of result:" msgstr "" "上記の操作は、必要に応じてロギングを設定した *後に* 行うべきです。上記の例で" "は、 :func:`~logging.basicConfig` の呼び出しが (``LoggerWriter`` インスタンス" "で上書きされる *前の* ``sys.stderr`` を使って) 設定を行います。そして、以下の" "ような結果を得るでしょう:" #: ../../howto/logging-cookbook.rst:4005 msgid "" ">>> print('Foo')\n" "INFO:demo:Foo\n" ">>> print('Bar', file=sys.stderr)\n" "WARNING:demo:Bar\n" ">>>" msgstr "" #: ../../howto/logging-cookbook.rst:4013 msgid "" "Of course, the examples above show output according to the format used by :" "func:`~logging.basicConfig`, but you can use a different formatter when you " "configure logging." msgstr "" "言うまでもなく上記の例は :func:`~logging.basicConfig` で使われている書式にも" "とづく出力を示していますが、ロギングの設定で異なるフォーマッタを使うことがで" "きます。" #: ../../howto/logging-cookbook.rst:4017 msgid "" "Note that with the above scheme, you are somewhat at the mercy of buffering " "and the sequence of write calls which you are intercepting. For example, " "with the definition of ``LoggerWriter`` above, if you have the snippet" msgstr "" "上記の例では、バッファリングや奪取した書き込み呼び出しのシーケンスの扱いにつ" "いてはなすがままになっています。たとえば、上記の ``LoggerWriter`` の定義で、" "次のようなコードの断片があったとします。" #: ../../howto/logging-cookbook.rst:4021 msgid "" "sys.stderr = LoggerWriter(logger, logging.WARNING)\n" "1 / 0" msgstr "" #: ../../howto/logging-cookbook.rst:4026 msgid "then running the script results in" msgstr "このスクリプトを実行すると以下のような結果が得られます。" #: ../../howto/logging-cookbook.rst:4028 msgid "" "WARNING:demo:Traceback (most recent call last):\n" "\n" "WARNING:demo: File \"/home/runner/cookbook-loggerwriter/test.py\", line 53, " "in \n" "\n" "WARNING:demo:\n" "WARNING:demo:main()\n" "WARNING:demo: File \"/home/runner/cookbook-loggerwriter/test.py\", line 49, " "in main\n" "\n" "WARNING:demo:\n" "WARNING:demo:1 / 0\n" "WARNING:demo:ZeroDivisionError\n" "WARNING:demo::\n" "WARNING:demo:division by zero" msgstr "" #: ../../howto/logging-cookbook.rst:4044 msgid "" "As you can see, this output isn't ideal. That's because the underlying code " "which writes to ``sys.stderr`` makes multiple writes, each of which results " "in a separate logged line (for example, the last three lines above). To get " "around this problem, you need to buffer things and only output log lines " "when newlines are seen. Let's use a slightly better implementation of " "``LoggerWriter``:" msgstr "" #: ../../howto/logging-cookbook.rst:4050 msgid "" "class BufferingLoggerWriter(LoggerWriter):\n" " def __init__(self, logger, level):\n" " super().__init__(logger, level)\n" " self.buffer = ''\n" "\n" " def write(self, message):\n" " if '\\n' not in message:\n" " self.buffer += message\n" " else:\n" " parts = message.split('\\n')\n" " if self.buffer:\n" " s = self.buffer + parts.pop(0)\n" " self.logger.log(self.level, s)\n" " self.buffer = parts.pop()\n" " for part in parts:\n" " self.logger.log(self.level, part)" msgstr "" #: ../../howto/logging-cookbook.rst:4069 msgid "" "This just buffers up stuff until a newline is seen, and then logs complete " "lines. With this approach, you get better output:" msgstr "" "この実装は改行があらわれるまでログをバッファリングし、行全体をログに出力する" "だけです。このアプローチにより、より適切な出力が得られます:" #: ../../howto/logging-cookbook.rst:4072 msgid "" "WARNING:demo:Traceback (most recent call last):\n" "WARNING:demo: File \"/home/runner/cookbook-loggerwriter/main.py\", line 55, " "in \n" "WARNING:demo: main()\n" "WARNING:demo: File \"/home/runner/cookbook-loggerwriter/main.py\", line 52, " "in main\n" "WARNING:demo: 1/0\n" "WARNING:demo:ZeroDivisionError: division by zero" msgstr "" #: ../../howto/logging-cookbook.rst:4085 msgid "Patterns to avoid" msgstr "避けるべきパターン" #: ../../howto/logging-cookbook.rst:4087 msgid "" "Although the preceding sections have described ways of doing things you " "might need to do or deal with, it is worth mentioning some usage patterns " "which are *unhelpful*, and which should therefore be avoided in most cases. " "The following sections are in no particular order." msgstr "" "これまでのセクションではログ出力を行うときに必要なこと、考慮すべきことなどを" "説明してきました。このセクションでは、 *役に立たない* 利用パターンについて触" "れます。これは多くの場合避けるべきことです。これらの説明はどこから読んでも構" "いません。" #: ../../howto/logging-cookbook.rst:4093 msgid "Opening the same log file multiple times" msgstr "同じログファイルを何度も開く" #: ../../howto/logging-cookbook.rst:4095 msgid "" "On Windows, you will generally not be able to open the same file multiple " "times as this will lead to a \"file is in use by another process\" error. " "However, on POSIX platforms you'll not get any errors if you open the same " "file multiple times. This could be done accidentally, for example by:" msgstr "" "Windowsでは同じファイルを何度も開くことができず「このファイルは他のプロセスか" "ら利用されています」というエラーが表示されます。しかし、POSIXプラットフォーム" "ではエラーがおきることなく、同じファイルを何度も開けます。これは次のように間" "違って使われる可能性があります。" #: ../../howto/logging-cookbook.rst:4100 msgid "" "Adding a file handler more than once which references the same file (e.g. by " "a copy/paste/forget-to-change error)." msgstr "" "同じファイルを指すファイルハンドラを1度以上追加する(例えばコピー&ペーストし" "て書き換え忘れによるエラー)。" #: ../../howto/logging-cookbook.rst:4103 msgid "" "Opening two files that look different, as they have different names, but are " "the same because one is a symbolic link to the other." msgstr "" "異なる名前を持つ、一見異なる2つのファイルを開くが、片方が他方へのシンボリック" "リンクとなっている。" #: ../../howto/logging-cookbook.rst:4106 msgid "" "Forking a process, following which both parent and child have a reference to " "the same file. This might be through use of the :mod:`multiprocessing` " "module, for example." msgstr "" "プロセスをフォークするが、その後親プロセスと子プロセスが同じファイルへの参照" "を維持する。これは例えば、 :mod:`multiprocessing` モジュールなどを使うと発生" "する可能性があります。" #: ../../howto/logging-cookbook.rst:4110 msgid "" "Opening a file multiple times might *appear* to work most of the time, but " "can lead to a number of problems in practice:" msgstr "" "ファイルを複数回開くことは、 *一見* 動作しているように見えますが、さまざまな" "問題を引き起こす可能性があります:" #: ../../howto/logging-cookbook.rst:4113 msgid "" "Logging output can be garbled because multiple threads or processes try to " "write to the same file. Although logging guards against concurrent use of " "the same handler instance by multiple threads, there is no such protection " "if concurrent writes are attempted by two different threads using two " "different handler instances which happen to point to the same file." msgstr "" "複数のスレッドが同一ファイルに書き出そうとすると、ログ出力が文字化けする可能" "性があります。ログモジュールは同じハンドラーのインスタンスに対して並列で利用" "しても正しく動くようになっていますが、同じファイルを参照する2つの異なるハンド" "ラーのインスタンスに対し、2つのスレッドから同時に書き込みをした場合にはそのよ" "うな保護は働きません。" #: ../../howto/logging-cookbook.rst:4119 msgid "" "An attempt to delete a file (e.g. during file rotation) silently fails, " "because there is another reference pointing to it. This can lead to " "confusion and wasted debugging time - log entries end up in unexpected " "places, or are lost altogether. Or a file that was supposed to be moved " "remains in place, and grows in size unexpectedly despite size-based rotation " "being supposedly in place." msgstr "" "(たとえばファイルのローテーションの間に) ファイルを削除しようとすると、その" "ファイルを指す別の参照が残っているために、何のエラーも発しないまま失敗しま" "す。これは混乱や不要なデバッグの時間のもととなる可能性があります - ログが思い" "もしない場所に記録されたり、完全に失われたりします。もしくは移動したと思われ" "ていたファイルが残っていたり、ファイルサイズにもとづくローテーションが行われ" "ているにもかかわらずファイルサイズが予想外に増加したりすることもあります。" #: ../../howto/logging-cookbook.rst:4126 msgid "" "Use the techniques outlined in :ref:`multiple-processes` to circumvent such " "issues." msgstr "" "この問題を回避するには :ref:`multiple-processes` で紹介したテクニックを使用し" "てください。" #: ../../howto/logging-cookbook.rst:4130 msgid "Using loggers as attributes in a class or passing them as parameters" msgstr "ロガーをクラスの属性にするか、パラメータで渡す" #: ../../howto/logging-cookbook.rst:4132 msgid "" "While there might be unusual cases where you'll need to do this, in general " "there is no point because loggers are singletons. Code can always access a " "given logger instance by name using ``logging.getLogger(name)``, so passing " "instances around and holding them as instance attributes is pointless. Note " "that in other languages such as Java and C#, loggers are often static class " "attributes. However, this pattern doesn't make sense in Python, where the " "module (and not the class) is the unit of software decomposition." msgstr "" "ロガーはシングルトンであるため、一般的には意味がなく、これを行う必要が出てく" "ることは滅多にありません。コードからは名前を使って ``logging." "getLogger(name)`` 経由でロガーインスタンスにアクセスできるため、インスタンス" "を持って回って、インスタンス属性として保持することは意味がありません。Javaや" "C#といった他の言語ではよく静的クラス属性にしてます。しかし、Pythonにおいては" "このパターンはクラスではなくモジュールがソフトウェア分解の単位となっているた" "め、無意味です。" #: ../../howto/logging-cookbook.rst:4141 msgid "" "Adding handlers other than :class:`~logging.NullHandler` to a logger in a " "library" msgstr "" "ライブラリ内でロガーに :class:`~logging.NullHandler` 以外のハンドラーを追加す" "る" #: ../../howto/logging-cookbook.rst:4143 msgid "" "Configuring logging by adding handlers, formatters and filters is the " "responsibility of the application developer, not the library developer. If " "you are maintaining a library, ensure that you don't add handlers to any of " "your loggers other than a :class:`~logging.NullHandler` instance." msgstr "" "ハンドラーやフォーマッター、フィルターを追加してログ出力をカスタマイズするの" "はライブラリ開発者ではなく、アプリケーション開発者の責務です。もしあなたがラ" "イブラリのメンテナンスをしているのであれば、 :class:`~logging.NullHandler` イ" "ンスタンス以外のロガーを追加してはいけない、ということを意味します。" #: ../../howto/logging-cookbook.rst:4149 msgid "Creating a lot of loggers" msgstr "大量のロガーを作成する" #: ../../howto/logging-cookbook.rst:4151 msgid "" "Loggers are singletons that are never freed during a script execution, and " "so creating lots of loggers will use up memory which can't then be freed. " "Rather than create a logger per e.g. file processed or network connection " "made, use the :ref:`existing mechanisms ` for passing " "contextual information into your logs and restrict the loggers created to " "those describing areas within your application (generally modules, but " "occasionally slightly more fine-grained than that)." msgstr "" "ロガーはシングルトンであり、スクリプトの実行中に解放されることがないため、大" "量のロガーを作成すると、メモリが解放されることなく消費されます。ファイルの処" "理単位やネットワーク接続単位でロガーを作るのではなく、 :ref:`既存のメカニズ" "ム ` を使ってコンテキスト依存の情報をログに渡し、ロガーはアプリ" "ケーション内の説明の単位(通常はモジュールだが、場合によってはそれよりも小さ" "い可能性もある)で作るように制限してください。" #: ../../howto/logging-cookbook.rst:4162 msgid "Other resources" msgstr "その他のリソース" #: ../../howto/logging-cookbook.rst:4166 msgid "Module :mod:`logging`" msgstr ":mod:`logging` モジュール" #: ../../howto/logging-cookbook.rst:4167 msgid "API reference for the logging module." msgstr "logging モジュールの API リファレンス。" #: ../../howto/logging-cookbook.rst:4169 msgid "Module :mod:`logging.config`" msgstr ":mod:`logging.config` モジュール" #: ../../howto/logging-cookbook.rst:4170 msgid "Configuration API for the logging module." msgstr "logging モジュールの環境設定 API です。" #: ../../howto/logging-cookbook.rst:4172 msgid "Module :mod:`logging.handlers`" msgstr ":mod:`logging.handlers` モジュール" #: ../../howto/logging-cookbook.rst:4173 msgid "Useful handlers included with the logging module." msgstr "logging モジュールに含まれる、便利なハンドラです。" #: ../../howto/logging-cookbook.rst:4175 msgid ":ref:`Basic Tutorial `" msgstr ":ref:`基本チュートリアル `" #: ../../howto/logging-cookbook.rst:4177 msgid ":ref:`Advanced Tutorial `" msgstr ":ref:`上級チュートリアル `"