当前位置:网站首页>PHP log base - monolog knowledge collation
PHP log base - monolog knowledge collation
2022-07-24 09:25:00 【Chon.Wang】
One 、 essential information
1.1 Basic introduction
You must have learned from other places
Monolog. No problem , Let me say it again , Manual formation .
MonologyesPHPA relatively complete and easy to expand log base .
MonologYou can send logs to files 、 mailbox 、 database 、socketsAnd all kinds of web services.
1.2 Related website
1.3 The log level
If not already installed Monolog , Please see the installation process below .
stay/vendor/monolog/monolog/src/Monolog/Logger.phpIn file , You can see DefinedLog level Class constantAndProtected static member properties $levels. That's according to a RFC5424 describe , Defined 8 Log level .# Log level constant , Top to bottom Level severity Higher and higher DEBUG = 100; # Debug level INFO = 200; # Information level NOTICE = 250; # Normal prompt level WARNING = 300; # Warning level ERROR = 400; # error level CRITICAL = 500; # Severity level ALERT = 550; # Alarm level EMERGENCY = 600; # emergency
Two 、composer install Monolog
If not already installed composer , Please install first. Composer.
Check me out. - Mac M1 install Composer
Check me out. - Official installation Composer technological process
2.1 install
# composer install monolog, Determine yourself PHP Version of
# What I have installed here is monolog V2.7.0
composer require monolog/monolog
2.2 Error handling
If there are any errors reported below , Please confirm your PHP Version in accordance with Monolog Of PHP Version for , Or download support for your current PHP Version of Monolog.
PHP Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.0". You are running 0.0.0.resolvent :
- stay
composer.jsonIn the documentconfigModule add"platform-check": false"config": { "platform-check": false }, "require": { "monolog/monolog": "^2.7.0" }
- perform
composer dumpcommand
3、 ... and 、 Introduction to basic usage
What's next , combination 3.4 The sample code And the understanding of manual operation will be more profound .
3.1 Formatter
FormatterIt is to convert the log content into the required format .List some common
Formatter, Others please/vendor/monolog/monolog/src/Monolog/FormatterSee... In the catalog .
1. Log information is converted into HTML form
<?php
use Monolog\Formatter\HtmlFormatter;
$dateFormat = "Y-m-d H:i:s"; # Customize the time format - Optional
# Convert log information into HTML form , It is mainly used for sending mail or generating log history pages
$html_formatter = new HtmlFormatter($dateFormat);
2. Log information is converted into JSON Format
<?php
use Monolog\Formatter\JsonFormatter;
# Turn into JSON Format
$json_formatter = new JsonFormatter();
3. Log information is converted into a line of string
The default format :
stay
/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.phpIn file , You can see the defined default Log format .public const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n";
<?php
use Monolog\Formatter\LineFormatter;
$dateFormat = "Y-m-d H:i:s"; # Customize the time format
# Convert log data into a line of characters , Customizable format
$output = "%datetime% > %level_name% > %channel% > %message% > %context% > %extra% \n "; # Customize the format of log content
$line_formatter = new LineFormatter($output, $dateFormat);
3.2 Handler
HandlerThat is, how to save the log .List some common
Handler, Others please/vendor/monolog/monolog/src/Monolog/HandlerSee... In the catalog .
HandlerIt is stored in stack , So it's first inhandlerAfter the call .
1. Write the log information PHP In the error log file
<?php
use Monolog\Handler\ErrorLogHandler;
$error_log_handler = new ErrorLogHandler();
$error_log_handler->setFormatter($line_formatter); # Define log content
$log->pushHandler($error_log_handler); # Push
2. Send the log information by email
<?php
use Monolog\Handler\NativeMailerHandler;
# Send the log information by email
$native_mailer_handler = new NativeMailerHandler(" Recipient email ", " Email subject ", " Sender's mailbox ");
$native_mailer_handler->setFormatter($html_formatter); # Define log content
$log->pushHandler($native_mailer_handler); # Push
3. Write log to local file
<?php
use Monolog\Handler\StreamHandler;
# Write log to local file
$stream_handler = new StreamHandler("./log/my_first_log.log");
$stream_handler->setFormatter($line_formatter); # Define log content
$log->pushHandler($stream_handler); # Push
4. To write the log locally, press... By default God Generated files
<?php
use Monolog\Handler\RotatingFileHandler;
# Write log to local file , By default, press God Generate log files
$rotating_file_handler = new RotatingFileHandler("./log/day_register.log");
$rotating_file_handler->setFormatter($json_formatter); # Define log content
$log->pushHandler($rotating_file_handler); # Push
3.3 Processor
ProcessorIs to add additional log content .
1. Customize additional log content
<?php
# adopt $record['extra'] return
$log->pushProcessor(function($record){
$record['extra']['age'] = 18;
$record['extra']['sex'] = ' male ';
return $record;
});
2. Script path 、 Line number 、 Class name related
<?php
use Monolog\Processor\IntrospectionProcessor;
# Processor - Extra save Script path 、 Line number 、 Class name Log data - Optional
$log->pushProcessor(new IntrospectionProcessor());
3. URI、IP、 Request mode 、 Request domain name 、 Source page
<?php
use Monolog\Processor\WebProcessor;
# Processor - Extra save UID Unique identifier Log data - Optional
$log->pushProcessor(new WebProcessor());
4. Generate UID Unique identifier
<?php
use Monolog\Processor\UidProcessor;
# Processor - Extra save UID Unique identifier Log data - Optional
$log->pushProcessor(new UidProcessor());
5. Git relevant
<?php
use Monolog\Processor\GitProcessor;
# Processor - Extra save Git Related log data - Optional
$log->pushProcessor(new GitProcessor());
6. Host name
<?php
use Monolog\Processor\HostnameProcessor;
# Processor - Extra save Host name Log data - Optional
$log->pushProcessor(new HostnameProcessor());
7. Peak memory usage
<?php
use Monolog\Processor\MemoryPeakUsageProcessor;
# Logger - Extra save Peak memory usage Log data - Optional
$log->pushProcessor(new MemoryPeakUsageProcessor());
8. Current memory usage
<?php
use Monolog\Processor\MemoryUsageProcessor;
# Processor - Extra save Current memory usage Log data - Optional
$log->pushProcessor(new MemoryUsageProcessor());
9. process ID
<?php
use Monolog\Processor\ProcessIdProcessor;
# Processor - Extra save process ID Log data - Optional
$log->pushProcessor(new ProcessIdProcessor());
Four 、 The sample code
<?php
require('vendor/autoload.php');
use Monolog\Logger;
use Monolog\Formatter\HtmlFormatter;
use Monolog\Formatter\JsonFormatter;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\ErrorLogHandler;
use Monolog\Handler\NativeMailerHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Processor\IntrospectionProcessor;
use Monolog\Processor\WebProcessor;
use Monolog\Processor\UidProcessor;
use Monolog\Processor\GitProcessor;
use Monolog\Processor\HostnameProcessor;
use Monolog\Processor\MemoryPeakUsageProcessor;
use Monolog\Processor\MemoryUsageProcessor;
use Monolog\Processor\ProcessIdProcessor;
# 1. Create a logging service
$log = new Logger(" Custom log service channel name "); # example : login_log
# 2. Custom time zone - Optional , By default UTC Time format
$log->setTimezone(new DateTimeZone('Asia/Shanghai'));
# 3. Customize the time format - Optional
$dateFormat = "Y-m-d H:i:s";
# 4. Formatter part ( According to functional requirements , Choose the right one Formatter)
# 4.1 Convert log information into HTML form , It is mainly used for sending mail or generating log history pages
$html_formatter = new HtmlFormatter($dateFormat);
# 4.2 Convert log data into JSON Format
$json_formatter = new JsonFormatter();
# 4.3 Convert log data into a line of characters , Customizable format
$output = "%datetime% > %level_name% > %channel% > %message% > %context% > %extra% \n "; # Log content format
$line_formatter = new LineFormatter($output, $dateFormat);
# 5. Handler part ( According to functional requirements , Choose the right one Handler)
# 5.1 Write the log information PHP In the error log file
# $error_log_handler = new ErrorLogHandler();
# $error_log_handler->setFormatter($line_formatter); # Define log content
# $log->pushHandler($error_log_handler); # Push
# 5.2 Send the log information by email
# $native_mailer_handler = new NativeMailerHandler(" Recipient email ", " Email subject ", " Sender's mailbox ");
# $native_mailer_handler->setFormatter($html_formatter); # Define log content
# $log->pushHandler($native_mailer_handler); # Push
# 5.3 Write log to local file
$stream_handler = new StreamHandler(" Log file absolute path "); # example : __DIR__ . /log/my_first_log.log
$stream_handler->setFormatter($line_formatter); # Define log content
$log->pushHandler($stream_handler); # Push
# 5.4 Write log to local file , By default, press God Generated log files
# $rotating_file_handler = new RotatingFileHandler(" Log file absolute path "); # example : __DIR__ . /log/my_first_log.log
# $rotating_file_handler->setFormatter($json_formatter); # Define log content
# $log->pushHandler($rotating_file_handler); # Push
# 6. Processor part ( According to functional requirements , Multiple options Processor)
# Customize additional data
$log->pushProcessor(function($record){
$record['extra']['age'] = 18;
$record['extra']['sex'] = ' male ';
return $record;
});
$log->pushProcessor(new IntrospectionProcessor());
# $log->pushProcessor(new WebProcessor());
# $log->pushProcessor(new UidProcessor());
# $log->pushProcessor(new GitProcessor());
# $log->pushProcessor(new HostnameProcessor());
# $log->pushProcessor(new MemoryPeakUsageProcessor());
# $log->pushProcessor(new MemoryUsageProcessor());
# $log->pushProcessor(new ProcessIdProcessor());
# 7. Add a record to the log , According to your own needs , Select a log level to record
$log->log(" Log level constant or log level number ", " Log message ", " Log contents ");
# example : $log->log(200, ' Registered users :', ['username'=>'Chon', 'height'=>175]);
# $log->debug('Message');
# $log->info('Message');
# $log->notice('Message);
# $log->warning('Message');
# $log->error('Message);
# $log->critical('Message');
# $log->alert('Message');
# $log->emergency('Message');
# 8. An example of saving a log
# 2022-07-20 15:31:32 > INFO > my_first_log > Registered users : > {"username":"Chon","height":175} > {"age":18,"sex":" male "}
边栏推荐
- Dorissql syntax Usage Summary
- Account 1-2
- Racecar multi-point navigation experiment based on ROS communication mechanism
- Understanding of magnetic parameters in Hall sensors
- What is the component customization event we are talking about?
- From single architecture to distributed architecture, there are many pits and bugs!
- 华为无线设备安全策略配置命令
- Opencv learning Day5
- 【汇编语言实战】(二)、编写一程序计算表达式w=v-(x+y+z-51)的值(含代码、过程截图)
- Introduction to common ansible modules
猜你喜欢

The detailed process of building discuz forum is easy to understand

如何通过NFT GO,来简要判断、分析NFT市场?

Leetcode skimming: dynamic planning 03 (climb stairs with minimum cost)
![[don't bother to strengthen learning] video notes (II) 1. What is Q-learning?](/img/4f/809adc96e30fad03a113acc3df4b61.png)
[don't bother to strengthen learning] video notes (II) 1. What is Q-learning?

What is the component customization event we are talking about?

唐宇迪opencv-背景建模

& 和 &&、| 和 || 的区别
![[don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?](/img/57/0ebff0839d2a2898472d3270fd13df.png)
[don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?

Build practical product help documents to improve user satisfaction

Let's test 5million pieces of data. How to use index acceleration reasonably?
随机推荐
Understanding of magnetic parameters in Hall sensors
[don't bother with reinforcement learning] video notes (I) 1. What is reinforcement learning?
链表——24. 两两交换链表中的节点
How to open the port number of the server, and the corresponding port of common network services
Asyncdata cross domain error after nuxt route switching
The difference between & &, | and |
SQL optimization principles
获取所有股票历史行情数据
Re6:读论文 LeSICiN: A Heterogeneous Graph-based Approach for Automatic Legal Statute Identification fro
Three tips for finding the latest trends on tiktok
[Luogu p3426] SZA template (string) (KMP)
Learning transformer: overall architecture and Implementation
[don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?
Aruba learning notes 06 wireless control AC basic configuration (CLI)
Detailed LinkedList
数据中台:始于阿里,兴于DaaS
详解LinkedList
Vector control of permanent magnet synchronous motor (I) -- mathematical model
Tiktok live broadcast with goods marketing play
UE5影视动画渲染MRQ分层学习笔记