当前位置:网站首页>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 "}
边栏推荐
- 链表——24. 两两交换链表中的节点
- Practice 4-6 number guessing game (15 points)
- Gin framework uses session and redis to realize distributed session & Gorm operation mysql
- Makefile variables and dynamic library static library
- Huawei wireless device security policy configuration command
- Android Version Description security privacy 13
- 【基于ROS的URDF练习实例】四轮机器人与摄像头的使用
- Aruba learning notes 06 wireless control AC basic configuration (CLI)
- Linked list - 24. Exchange nodes in the linked list in pairs
- [don't bother to strengthen learning] video notes (II) 1. What is Q-learning?
猜你喜欢
![[example of URDF exercise based on ROS] use of four wheeled robot and camera](/img/c5/babce5c6921b9cb54f018dc83a3b87.jpg)
[example of URDF exercise based on ROS] use of four wheeled robot and camera
![[translation] integration challenges in microservice architecture using grpc and rest](/img/88/53f4c2061b538b3201475ba51449ff.jpg)
[translation] integration challenges in microservice architecture using grpc and rest

Opencv learning Day5

JS locate Daquan to get the brother, parent and child elements of the node, including robot instances
![[don't bother to strengthen learning] video notes (IV) 1. What is dqn?](/img/74/51219a19595f93e7a85449f54d354d.png)
[don't bother to strengthen learning] video notes (IV) 1. What is dqn?

我们说的组件自定义事件到底是什么?

From single architecture to distributed architecture, there are many pits and bugs!

Hands on deep learning (VII) -- bounding box and anchor box

Android system security - 5.2-apk V1 signature introduction

Android Version Description security privacy 13
随机推荐
Little dolphin "transformed" into a new intelligent scheduling engine, which can be explained in simple terms in the practical development and application of DDS
Three tips for finding the latest trends on tiktok
Little dolphin "transformed" into a new intelligent scheduling engine, which can be explained in simple terms in the practical development and application of DDS
DSP development, using CCS software to establish engineering and burning
One click openstack single point mode environment deployment - preliminary construction
【笔记】什么是内核/用户空间 从CPU如何运行程序讲起
Re6:读论文 LeSICiN: A Heterogeneous Graph-based Approach for Automatic Legal Statute Identification fro
Let's test 5million pieces of data. How to use index acceleration reasonably?
Problem: filesystemversionexception: you have version null and I want version 8
Data center: started in Alibaba and started in Daas
Racecar multi-point navigation experiment based on ROS communication mechanism
dp最长公共子序列详细版本(LCS)
Android系统安全 — 5.3-APK V2签名介绍
Will your NFT disappear? Dfinity provides the best solution for NFT storage
JS locate Daquan to get the brother, parent and child elements of the node, including robot instances
(5) Cloud integrated gateway gateway +swagger documentation tool
Dorissql syntax Usage Summary
[Luogu p5410] [template] extend KMP (Z function) (string)
Huawei wireless device security policy configuration command
IdentityServer4入门