{"id":24618007,"url":"https://github.com/nekonomokochan/php-json-logger","last_synced_at":"2025-05-07T06:02:24.093Z","repository":{"id":57024758,"uuid":"135059307","full_name":"nekonomokochan/php-json-logger","owner":"nekonomokochan","description":"LoggingLibrary for PHP. Output by JSON Format","archived":false,"fork":false,"pushed_at":"2019-02-18T06:14:08.000Z","size":154,"stargazers_count":10,"open_issues_count":0,"forks_count":5,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-15T03:03:11.757Z","etag":null,"topics":["logger","monolog","php","php-library","php7","psr-3"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nekonomokochan.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-05-27T15:35:51.000Z","updated_at":"2022-02-12T07:30:05.000Z","dependencies_parsed_at":"2022-08-23T15:00:18.178Z","dependency_job_id":null,"html_url":"https://github.com/nekonomokochan/php-json-logger","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nekonomokochan%2Fphp-json-logger","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nekonomokochan%2Fphp-json-logger/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nekonomokochan%2Fphp-json-logger/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nekonomokochan%2Fphp-json-logger/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nekonomokochan","download_url":"https://codeload.github.com/nekonomokochan/php-json-logger/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252823910,"owners_count":21809711,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["logger","monolog","php","php-library","php7","psr-3"],"created_at":"2025-01-24T23:49:28.780Z","updated_at":"2025-05-07T06:02:24.041Z","avatar_url":"https://github.com/nekonomokochan.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# php-json-logger\n[![Latest Stable Version](https://poser.pugx.org/nekonomokochan/php-json-logger/v/stable)](https://packagist.org/packages/nekonomokochan/php-json-logger)\n[![Total Downloads](https://poser.pugx.org/nekonomokochan/php-json-logger/downloads)](https://packagist.org/packages/nekonomokochan/php-json-logger)\n[![Latest Unstable Version](https://poser.pugx.org/nekonomokochan/php-json-logger/v/unstable)](https://packagist.org/packages/nekonomokochan/php-json-logger)\n[![License](https://poser.pugx.org/nekonomokochan/php-json-logger/license)](https://packagist.org/packages/nekonomokochan/php-json-logger)\n[![Monthly Downloads](https://poser.pugx.org/nekonomokochan/php-json-logger/d/monthly)](https://packagist.org/packages/nekonomokochan/php-json-logger)\n[![Daily Downloads](https://poser.pugx.org/nekonomokochan/php-json-logger/d/daily)](https://packagist.org/packages/nekonomokochan/php-json-logger)\n[![composer.lock](https://poser.pugx.org/nekonomokochan/php-json-logger/composerlock)](https://packagist.org/packages/nekonomokochan/php-json-logger)\n[![Build Status](https://travis-ci.org/nekonomokochan/php-json-logger.svg?branch=master)](https://travis-ci.org/nekonomokochan/php-json-logger)\n[![Coverage Status](https://coveralls.io/repos/github/nekonomokochan/php-json-logger/badge.svg?branch=master)](https://coveralls.io/github/nekonomokochan/php-json-logger?branch=master)\n\nLoggingLibrary for PHP. Output by JSON Format\n\nThis Library is mainly intended for use in web applications.\n\n## Getting Started\n\n### Install composer package\n\n```\ncomposer require nekonomokochan/php-json-logger\n```\n\n## How To Use\n\n### Basic usage\n\n```php\n\u003c?php\nuse Nekonomokochan\\PhpJsonLogger\\LoggerBuilder;\n\n$context = [\n    'title' =\u003e 'Test',\n    'price' =\u003e 4000,\n    'list'  =\u003e [1, 2, 3],\n    'user'  =\u003e [\n        'id'   =\u003e 100,\n        'name' =\u003e 'keitakn',\n    ],\n];\n\n$loggerBuilder = new LoggerBuilder();\n$logger = $loggerBuilder-\u003ebuild();\n$logger-\u003einfo('🐱', $context);\n```\n\nIt is output as follows.\n\n```json\n{\n    \"log_level\": \"INFO\",\n    \"message\": \"🐱\",\n    \"channel\": \"PhpJsonLogger\",\n    \"trace_id\": \"35b627ce-55e0-4729-9da0-fbda2a7d817d\",\n    \"file\": \"\\/home\\/vagrant\\/php-json-logger\\/tests\\/LoggerTest.php\",\n    \"line\": 42,\n    \"context\": {\n        \"title\": \"Test\",\n        \"price\": 4000,\n        \"list\": [\n            1,\n            2,\n            3\n        ],\n        \"user\": {\n            \"id\": 100,\n            \"name\": \"keitakn\"\n        }\n    },\n    \"remote_ip_address\": \"127.0.0.1\",\n    \"server_ip_address\": \"127.0.0.1\",\n    \"user_agent\": \"unknown\",\n    \"datetime\": \"2018-06-04 17:21:03.631409\",\n    \"timezone\": \"Asia\\/Tokyo\",\n    \"process_time\": 631.50811195373535\n}\n```\n\nThe unit of `process_time` is ms(millisecond).\n\n#### How to change output filepath\n\nDefault output filepath is `/tmp/php-json-logger-yyyy-mm-dd.log` .\n\nIf you want to change the output filepath, please set the output filepath to the builder class.\n\n```php\n\u003c?php\nuse Nekonomokochan\\PhpJsonLogger\\LoggerBuilder;\n\n$fileName = '/tmp/test-php-json-logger.log';\n\n$context = [\n    'cat'    =\u003e '🐱',\n    'dog'    =\u003e '🐶',\n    'rabbit' =\u003e '🐰',\n];\n\n$loggerBuilder = new LoggerBuilder();\n$loggerBuilder-\u003esetFileName($fileName);\n$logger = $loggerBuilder-\u003ebuild();\n$logger-\u003einfo('testSetLogFileName', $context);\n```\n\nThe output filepath is `/tmp/test-php-json-logger-yyyy-mm-dd.log` .\n\nIt is output as follows.\n\n```json\n{\n    \"log_level\": \"INFO\",\n    \"message\": \"testSetLogFileName\",\n    \"channel\": \"PhpJsonLogger\",\n    \"trace_id\": \"20f39cdb-dbd8-470c-babd-093a2974d169\",\n    \"file\": \"\\/home\\/vagrant\\/php-json-logger\\/tests\\/LoggerTest.php\",\n    \"line\": 263,\n    \"context\": {\n        \"cat\": \"🐱\",\n        \"dog\": \"🐶\",\n        \"rabbit\": \"🐰\"\n    },\n    \"remote_ip_address\": \"127.0.0.1\",\n    \"server_ip_address\": \"127.0.0.1\",\n    \"user_agent\": \"unknown\",\n    \"datetime\": \"2018-06-05 11:28:03.214995\",\n    \"timezone\": \"Asia\\/Tokyo\",\n    \"process_time\": 215.09790420532227\n}\n```\n\n#### How to Set `trace_id`\n\nAny value can be set for `trace_id`.\n\nThis will help you when looking for logs you want.\n\n```php\n\u003c?php\nuse Nekonomokochan\\PhpJsonLogger\\LoggerBuilder;\n\n$context = [\n    'name' =\u003e 'keitakn',\n];\n\n$loggerBuilder = new LoggerBuilder();\n$loggerBuilder-\u003esetTraceId('MyTraceID');\n$logger = $loggerBuilder-\u003ebuild();\n$logger-\u003einfo('testSetTraceIdIsOutput', $context);\n```\n\nIt is output as follows.\n\n```json\n{\n    \"log_level\": \"INFO\",\n    \"message\": \"testSetTraceIdIsOutput\",\n    \"channel\": \"PhpJsonLogger\",\n    \"trace_id\": \"MyTraceID\",\n    \"file\": \"\\/home\\/vagrant\\/php-json-logger\\/tests\\/LoggerTest.php\",\n    \"line\": 214,\n    \"context\": {\n        \"name\": \"keitakn\"\n    },\n    \"remote_ip_address\": \"127.0.0.1\",\n    \"server_ip_address\": \"127.0.0.1\",\n    \"user_agent\": \"unknown\",\n    \"datetime\": \"2018-06-05 11:36:02.394269\",\n    \"timezone\": \"Asia\\/Tokyo\",\n    \"process_time\": 394.35911178588867\n}\n```\n\n#### How to change logLevel\n\nPlease use `\\Nekonomokochan\\PhpJsonLogger\\LoggerBuilder::setLogLevel()` .\n\nFor example, the following code does not output logs.\n\nBecause the level is set to `CRITICAL`.\n\n```php\n\u003c?php\nuse Nekonomokochan\\PhpJsonLogger\\LoggerBuilder;\n\n$context = [\n    'cat'    =\u003e '🐱',\n    'dog'    =\u003e '🐶',\n    'rabbit' =\u003e '🐰',\n];\n\n$loggerBuilder = new LoggerBuilder();\n$loggerBuilder-\u003esetLogLevel(LoggerBuilder::CRITICAL);\n$logger = $loggerBuilder-\u003ebuild();\n$logger-\u003einfo('testSetLogLevel', $context);\n```\n\nYou can set the following values for `logLevel` .\n\nThese are the same as `logLevel` defined in [Monolog](https://github.com/Seldaek/monolog).\n\n- DEBUG = 100\n- INFO = 200\n- NOTICE = 250\n- WARNING = 300\n- ERROR = 400\n- CRITICAL = 500\n- ALERT = 550\n- EMERGENCY = 600\n\n#### How to change channel\n\nDefault channel is `PhpJsonLogger`.\n\nIf you want to change the channel, you can change it with the following code.\n\n```php\n$loggerBuilder = new LoggerBuilder();\n$loggerBuilder-\u003esetChannel('My Favorite Animals');\n```\n\nFor example, the output is as follows.\n\n```json\n{\n    \"log_level\": \"INFO\",\n    \"message\": \"testCanSetChannel\",\n    \"channel\": \"My Favorite Animals\",\n    \"trace_id\": \"4b8aa070-a533-4376-9bf5-270c8fcc6d87\",\n    \"file\": \"\\/home\\/vagrant\\/php-json-logger\\/tests\\/Logger\\/LoggerTest.php\",\n    \"line\": 347,\n    \"context\": {\n        \"animals\": \"🐱🐶🐰🐱🐹\"\n    },\n    \"remote_ip_address\": \"127.0.0.1\",\n    \"server_ip_address\": \"127.0.0.1\",\n    \"user_agent\": \"unknown\",\n    \"datetime\": \"2018-06-07 17:56:48.538117\",\n    \"timezone\": \"Asia\\/Tokyo\",\n    \"process_time\": 538.48695755004883\n}\n```\n\n#### How to change Log Rotation Date\n\nThis is the default setting to save logs for 7 days.\n\nIf you want to change the log Rotation date, you can change it with the following code.\n\nThe following code sets the log retention period to 2 days.\n\n```php\n$loggerBuilder = new LoggerBuilder();\n$loggerBuilder-\u003esetMaxFiles(2);\n```\n\n### Extend and use `\\Nekonomokochan\\PhpJsonLogger\\JsonFormatter`\n\nYou can make your own `\\Monolog\\Logger` using only `\\Nekonomokochan\\PhpJsonLogger\\JsonFormatter`.\n\nThis method is useful when you need `\\Monolog\\Logger` in web application framework(e.g. [Laravel](https://github.com/laravel/laravel)).\n\nThe following is sample code.\n\n```php\n\u003c?php\nuse Monolog\\Logger;\nuse Monolog\\Handler\\RotatingFileHandler;\nuse Monolog\\Processor\\IntrospectionProcessor;\nuse Nekonomokochan\\PhpJsonLogger\\JsonFormatter;\n\n$logFileName = '/tmp/extended-monolog-test.log';\n\n// create extendedMonolog Instance\n$formatter = new JsonFormatter();\n\n$rotating = new RotatingFileHandler(\n    $logFileName,\n    7,\n    Logger::INFO\n);\n$rotating-\u003esetFormatter($formatter);\n\n$introspection = new IntrospectionProcessor(\n    Logger::INFO,\n    ['Nekonomokochan\\\\PhpJsonLogger\\\\'],\n    0\n);\n\n$extraRecords = function ($record) {\n    $record['extra']['trace_id'] = 'ExtendedMonologTestTraceId';\n    $record['extra']['created_time'] = microtime(true);\n\n    return $record;\n};\n\n$extendedMonolog = new Logger(\n    'ExtendedMonolog',\n    [$rotating],\n    [$introspection, $extraRecords]\n);\n\n// output info log\n$context = [\n    'cat'    =\u003e '🐱',\n    'dog'    =\u003e '🐶',\n    'rabbit' =\u003e '🐰',\n];\n\n$extendedMonolog-\u003einfo('outputInfoLogTest', $context);\n```\n\nIt is output to `extended-monolog-test-yyyy-mm-dd.log` as follows\n\n```json\n{\n    \"log_level\": \"INFO\",\n    \"message\": \"outputInfoLogTest\",\n    \"channel\": \"ExtendedMonolog\",\n    \"trace_id\": \"ExtendedMonologTestTraceId\",\n    \"file\": \"\\/home\\/vagrant\\/php-json-logger\\/tests\\/ExtendedMonologTest.php\",\n    \"line\": 85,\n    \"context\": {\n        \"cat\": \"🐱\",\n        \"dog\": \"🐶\",\n        \"rabbit\": \"🐰\"\n    },\n    \"remote_ip_address\": \"127.0.0.1\",\n    \"server_ip_address\": \"127.0.0.1\",\n    \"user_agent\": \"unknown\",\n    \"datetime\": \"2018-06-06 17:14:26.042013\",\n    \"timezone\": \"Asia\\/Tokyo\",\n    \"process_time\": 0.1678466796875\n}\n```\n\nThe following code is necessary to output `trace_id` and `process_time`.\n\n```php\n\u003c?php\n$extraRecords = function ($record) {\n    $record['extra']['trace_id'] = 'ExtendedMonologTestTraceId';\n    $record['extra']['created_time'] = microtime(true);\n\n    return $record;\n};\n```\n\nThe code below is the code necessary to normally display the stack trace with JSON.\n\n```php\n\u003c?php\n$introspection = new IntrospectionProcessor(\n    Logger::INFO,\n    ['Nekonomokochan\\\\PhpJsonLogger\\\\'],\n    0\n);\n```\n\nTo output the stack trace to the log, execute the following code.\n\n```php\n\u003c?php\n$exception = new \\Exception('ExtendedMonologTest.outputErrorLog', 500);\n$context = [\n    'cat'    =\u003e '🐱(=^・^=)🐱',\n    'dog'    =\u003e '🐶Uo･ｪ･oU🐶',\n    'rabbit' =\u003e '🐰🐰🐰',\n];\n\n$extendedMonolog-\u003eerror(\n    get_class($exception),\n    $this-\u003eformatPhpJsonLoggerErrorsContext($exception, $context)\n);\n```\n\nPlease pay attention to the part `$this-\u003eformatPhpJsonLoggerErrorsContext($exception, $context)`.\n\nThis is necessary processing to format the error log into JSON and output it.\n\nThis is the method implemented in `\\Nekonomokochan\\PhpJsonLogger\\ErrorsContextFormat`.\n\nIt is output to `extended-monolog-test-yyyy-mm-dd.log` as follows.\n\nIf you want to know more detailed usage, please look at `php-json-logger/tests/ExtendedMonologTest.php`.\n\n```json\n{\n    \"log_level\": \"ERROR\",\n    \"message\": \"Exception\",\n    \"channel\": \"PhpJsonLogger\",\n    \"trace_id\": \"ExtendedMonologTestTraceId\",\n    \"file\": \"\\/home\\/vagrant\\/php-json-logger\\/tests\\/ExtendedMonologTest.php\",\n    \"line\": 126,\n    \"context\": {\n        \"cat\": \"🐱(=^・^=)🐱\",\n        \"dog\": \"🐶Uo･ｪ･oU🐶\",\n        \"rabbit\": \"🐰🐰🐰\"\n    },\n    \"remote_ip_address\": \"127.0.0.1\",\n    \"server_ip_address\": \"127.0.0.1\",\n    \"user_agent\": \"unknown\",\n    \"datetime\": \"2018-06-06 17:37:57.440757\",\n    \"timezone\": \"Asia\\/Tokyo\",\n    \"process_time\": 0.16093254089355469,\n    \"errors\": {\n        \"message\": \"ExtendedMonologTest.outputErrorLog\",\n        \"code\": 500,\n        \"file\": \"\\/home\\/vagrant\\/php-json-logger\\/tests\\/ExtendedMonologTest.php\",\n        \"line\": 117,\n        \"trace\": [\n            \"#0 \\/home\\/vagrant\\/php-json-logger\\/vendor\\/phpunit\\/phpunit\\/src\\/Framework\\/TestCase.php(1145): Nekonomokochan\\\\Tests\\\\ExtendedMonologTest-\u003eoutputErrorLog()\",\n            \"#1 \\/home\\/vagrant\\/php-json-logger\\/vendor\\/phpunit\\/phpunit\\/src\\/Framework\\/TestCase.php(840): PHPUnit\\\\Framework\\\\TestCase-\u003erunTest()\",\n            \"#2 \\/home\\/vagrant\\/php-json-logger\\/vendor\\/phpunit\\/phpunit\\/src\\/Framework\\/TestResult.php(645): PHPUnit\\\\Framework\\\\TestCase-\u003erunBare()\",\n            \"#3 \\/home\\/vagrant\\/php-json-logger\\/vendor\\/phpunit\\/phpunit\\/src\\/Framework\\/TestCase.php(798): PHPUnit\\\\Framework\\\\TestResult-\u003erun()\",\n            \"#4 \\/home\\/vagrant\\/php-json-logger\\/vendor\\/phpunit\\/phpunit\\/src\\/Framework\\/TestSuite.php(776): PHPUnit\\\\Framework\\\\TestCase-\u003erun()\",\n            \"#5 \\/home\\/vagrant\\/php-json-logger\\/vendor\\/phpunit\\/phpunit\\/src\\/TextUI\\/TestRunner.php(529): PHPUnit\\\\Framework\\\\TestSuite-\u003erun()\",\n            \"#6 \\/home\\/vagrant\\/php-json-logger\\/vendor\\/phpunit\\/phpunit\\/src\\/TextUI\\/Command.php(198): PHPUnit\\\\TextUI\\\\TestRunner-\u003edoRun()\",\n            \"#7 \\/home\\/vagrant\\/php-json-logger\\/vendor\\/phpunit\\/phpunit\\/src\\/TextUI\\/Command.php(151): PHPUnit\\\\TextUI\\\\Command-\u003erun()\",\n            \"#8 \\/home\\/vagrant\\/php-json-logger\\/vendor\\/phpunit\\/phpunit\\/phpunit(53): PHPUnit\\\\TextUI\\\\Command::main()\"\n        ]\n    }\n}\n```\n\n### Notification To Slack\n\nTo send the log to Slack please execute the following code.\n\nThis code will be sent to slack if the log level is `CRITICAL` or higher.\n\n```php\n\u003c?php\nuse Nekonomokochan\\PhpJsonLogger\\LoggerBuilder;\nuse Nekonomokochan\\PhpJsonLogger\\SlackHandlerBuilder;\n\n$exception = new \\Exception('TestException', 500);\n$context = [\n    'name'  =\u003e 'keitakn',\n    'email' =\u003e 'dummy@email.com',\n];\n\n$slackToken = 'YOUR_SLACK_TOKEN';\n$slackChannel = 'YOUR_SLACK_CHANNEL';\n\n$slackHandlerBuilder = new SlackHandlerBuilder($slackToken, $slackChannel);\n$slackHandlerBuilder-\u003esetLevel(LoggerBuilder::CRITICAL);\n\n$loggerBuilder = new LoggerBuilder();\n$loggerBuilder-\u003esetFileName($this-\u003eoutputFileBaseName);\n$loggerBuilder-\u003esetSlackHandler($slackHandlerBuilder-\u003ebuild());\n$logger = $loggerBuilder-\u003ebuild();\n$logger-\u003ecritical($exception, $context);\n```\n\n### Use in Docker\n\nPlease use `LoggerBuilder.setUseInDocker` in order to use it on Docker.\n\nWhen setUseInDocker is set to true, no file output is done and the log is output as `stdout`.\n\n```php\n\u003c?php\nuse Nekonomokochan\\PhpJsonLogger\\LoggerBuilder;\n\n$exception = new \\Exception('TestException', 500);\n$context = [\n    'name'  =\u003e 'keitakn',\n    'email' =\u003e 'dummy@email.com',\n];\n\n$loggerBuilder = new LoggerBuilder();\n$loggerBuilder-\u003esetFileName($this-\u003eoutputFileBaseName);\n$loggerBuilder-\u003esetUseInDocker(true);\n$logger = $loggerBuilder-\u003ebuild();\n$logger-\u003ecritical($exception, $context);\n```\n\n### Caution\n\n`\\Nekonomokochan\\PhpJsonLogger\\Logger` is a subclass that extends `\\Monolog\\Logger`\n\nYou can use it like `\\Monolog\\Logger`.\n\nHowever, for the following methods, you can pass only classes that extend `\\Exception` or `\\Error` as arguments.\n\n- `\\Nekonomokochan\\PhpJsonLogger\\Logger::error()`\n- `\\Nekonomokochan\\PhpJsonLogger\\Logger::critical()`\n- `\\Nekonomokochan\\PhpJsonLogger\\Logger::alert()`\n- `\\Nekonomokochan\\PhpJsonLogger\\Logger::emergency()`\n\nIn case of violation, `\\Nekonomokochan\\PhpJsonLogger\\Logger` will Throw `\\Nekonomokochan\\PhpJsonLogger\\InvalidArgumentException`\n\n## License\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnekonomokochan%2Fphp-json-logger","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnekonomokochan%2Fphp-json-logger","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnekonomokochan%2Fphp-json-logger/lists"}