国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
基本用法
核心概念
日志等級
用法詳解
多個handler
添加額外的數(shù)據(jù)
使用上下文
使用processor
頻道的使用
Handler
Formatter
Processor
擴展handler
參考
Home Backend Development PHP Tutorial 【PHP類庫】Monolog

【PHP類庫】Monolog

Jun 23, 2016 pm 01:34 PM

Monolog是PHP的一個日志類庫。相比于其他的日志類庫,它有以下的特點:

  • 功能強大??梢园讶罩景l(fā)送到文件、socket、郵箱、數(shù)據(jù)庫和各種web services。
  • 遵循PSR3的接口規(guī)范??梢院茌p易的替換成其他遵循同一規(guī)范的日志類庫。
  • 良好的擴展性。通過Handler、Formatter和Processor這幾個接口,可以對Monolog類庫進行各種擴展和自定義。

基本用法

安裝最新版本:

composer require monolog/monolog

要求PHP版本為5.3以上。

php<?phpuse Monolog\Logger;use Monolog\Handler\StreamHandler;// 創(chuàng)建日志頻道$log = new Logger('name');$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));// 添加日志記錄$log->addWarning('Foo');$log->addError('Bar');

核心概念

每一個Logger實例都包含一個頻道名(channel)和handler的堆棧。當你添加一條記錄時,記錄會依次通過handler堆棧的處理。而每個handler也可以決定是否把記錄傳遞到下一個堆棧里的下一個handler。

通過handler,我們可以實現(xiàn)一些復雜的日志操作。例如我們把StreamHandler放在堆棧的最下面,那么所有的日志記錄最終都會寫到硬盤文件里。同時我們把MailHandler放在堆棧的最上面,通過設置日志等級把錯誤日志通過郵件發(fā)送出去。Handler里有個$bubble屬性,這個屬性定義了handler是否攔截記錄不讓它流到下一個handler。所以如果我們把MailHandler的$bubble參數(shù)設置為false,則出現(xiàn)錯誤日志時,日志會通過MailHandler發(fā)送出去,而不會經(jīng)過StreamHandler寫到硬盤上。

Logger可以創(chuàng)建多個,每個都可以定義自己的頻道名和handler堆棧。handler可以在多個Logger中共享。頻道名會反映在日志里,方便我們查看和過濾日志記錄。

如果沒有指定日志格式(Formatter),Handler會使用默認的Formatter。

日志的等級不能自定義,目前使用的是RFC 5424里定義的8個等級:debug、info、notice、warning、error、critical、alert和emergency。如果對日志記錄有其他的需求,可以通過Processo對日志記錄添加內容。

日志等級

  • DEBUG (100): 詳細的debug信息。
  • INFO (200): 關鍵事件。
  • NOTICE (250): 普通但是重要的事件。
  • WARNING (300): 出現(xiàn)非錯誤的異常。
  • ERROR (400): 運行時錯誤,但是不需要立刻處理。
  • CRITICA (500): 嚴重錯誤。
  • EMERGENCY (600): 系統(tǒng)不可用。

用法詳解

多個handler

php<?phpuse Monolog\Logger;use Monolog\Handler\StreamHandler;use Monolog\Handler\FirePHPHandler;// 創(chuàng)建Logger實例$logger = new Logger('my_logger');// 添加handler$logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG));$logger->pushHandler(new FirePHPHandler());// 開始使用$logger->addInfo('My logger is now ready');

第一步我們先創(chuàng)建一個Logger實例,傳入的是頻道名,這個頻道名可以用于區(qū)分多個Logger實例。

實例本身并不知道如何處理日志記錄,它是通過handler進行處理的。handler可以設置多個,例如上面的例子設置了兩個handler,可以對日志記錄進行兩種不同方式的處理。

需要注意的是,由于handler是采用堆棧的方式保存,所以后面添加的handler位于棧頂,會首先被調用。

添加額外的數(shù)據(jù)

Monolog有兩種方式對日志添加額外的信息。

使用上下文

第一個方法是使用$context參數(shù),傳入一個數(shù)組:

php<?php$logger->addInfo('Adding a new user', array('username' => 'Seldaek'));

使用processor

第二個方法是使用processor。processor可以是任何可調用的方法,這些方法把日志記錄作為參數(shù),然后經(jīng)過處理修改extra部分后返回。

php<?php$logger->pushProcessor(function ($record) {    $record['extra']['dummy'] = 'Hello world!';    return $record;});

Processor不一定要綁定在Logger實例上,也可以綁定到某個具體的handler上。使用handler實例的pushProcessor方法進行綁定。

頻道的使用

使用頻道名可以對日志進行分類,這在大型的應用上是很有用的。通過頻道名,可以很容易的對日志記錄進行刷選。

例如我們想在同一個日志文件里記錄不同模塊的日志,我們可以把相同的handler綁定到不同的Logger實例上,這些實例使用不同的頻道名:

php<?phpuse Monolog\Logger;use Monolog\Handler\StreamHandler;use Monolog\Handler\FirePHPHandler;// 創(chuàng)建handler$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG);$firephp = new FirePHPHandler();// 創(chuàng)建應用的主要logger$logger = new Logger('my_logger');$logger->pushHandler($stream);$logger->pushHandler($firephp);// 通過不同的頻道名創(chuàng)建一個用于安全相關的logger$securityLogger = new Logger('security');$securityLogger->pushHandler($stream);$securityLogger->pushHandler($firephp);

Handler

Monolog內置很多很實用的handler,它們幾乎囊括了各種的使用場景,這里介紹一些使用的:
StreamHandler:把記錄寫進PHP流,主要用于日志文件。
SyslogHandler:把記錄寫進syslog。
ErrorLogHandler:把記錄寫進PHP錯誤日志。
NativeMailerHandler:使用PHP的mail()函數(shù)發(fā)送日志記錄。
SocketHandler:通過socket寫日志。

php<?phpuse Monolog\Logger;use Monolog\Handler\SocketHandler;// Create the logger$logger = new Logger('my_logger');// Create the handler$handler = new SocketHandler('unix:///var/log/httpd_app_log.socket');$handler->setPersistent(true);// Now add the handler$logger->pushHandler($handler, Logger::DEBUG);// You can now use your logger$logger->addInfo('My logger is now ready');

AmqpHandler:把記錄寫進兼容amqp協(xié)議的服務。
BrowserConsoleHandler:把日志記錄寫到瀏覽器的控制臺。由于是使用瀏覽器的console對象,需要看瀏覽器是否支持。
RedisHandler:把記錄寫進Redis。
MongoDBHandler:把記錄寫進Mongo。
ElasticSearchHandler:把記錄寫到ElasticSearch服務。
BufferHandler:允許我們把日志記錄緩存起來一次性進行處理。

更多的Handler請看https://github.com/Seldaek/monolog#handlers。

Formatter

同樣的,這里介紹幾個自帶的Formatter:
LineFormatter:把日志記錄格式化成一行字符串。
HtmlFormatter:把日志記錄格式化成HTML表格,主要用于郵件。
JsonFormatter:把日志記錄編碼成JSON格式。
LogstashFormatter:把日志記錄格式化成logstash的事件JSON格式。
ElasticaFormatter:把日志記錄格式化成ElasticSearch使用的數(shù)據(jù)格式。

更多的Formatter請看https://github.com/Seldaek/monolog#formatters。

Processor

前面說過,Processor可以為日志記錄添加額外的信息,Monolog也提供了一些很實用的processor:
IntrospectionProcessor:增加當前腳本的文件名和類名等信息。
WebProcessor:增加當前請求的URI、請求方法和訪問IP等信息。
MemoryUsageProcessor:增加當前內存使用情況信息。
MemoryPeakUsageProcessor:增加內存使用高峰時的信息。

更多的Processor請看https://github.com/Seldaek/monolog#processors。

擴展handler

Monolog內置了很多handler,但是并不是所有場景都能覆蓋到,有時需要自己去定制handler。寫一個handler并不難,只需要實現(xiàn)Monolog\Handler\HandlerInterface這個接口即可。

下面這個例子實現(xiàn)了把日志記錄寫到數(shù)據(jù)庫里。我們不需要把接口里的方法全部實現(xiàn)一次,可以直接使用Monolog提供的抽象類AbstractProcessingHandler進行繼承,實現(xiàn)里面的write方法即可。

php<?phpuse Monolog\Logger;use Monolog\Handler\AbstractProcessingHandler;class PDOHandler extends AbstractProcessingHandler{    private $initialized = false;    private $pdo;    private $statement;    public function __construct(PDO $pdo, $level = Logger::DEBUG, $bubble = true)    {        $this->pdo = $pdo;        parent::__construct($level, $bubble);    }    protected function write(array $record)    {        if (!$this->initialized) {            $this->initialize();        }        $this->statement->execute(array(            'channel' => $record['channel'],            'level' => $record['level'],            'message' => $record['formatted'],            'time' => $record['datetime']->format('U'),        ));    }    private function initialize()    {        $this->pdo->exec(            'CREATE TABLE IF NOT EXISTS monolog '            .'(channel VARCHAR(255), level INTEGER, message LONGTEXT, time INTEGER UNSIGNED)'        );        $this->statement = $this->pdo->prepare(            'INSERT INTO monolog (channel, level, message, time) VALUES (:channel, :level, :message, :time)'        );    }}

然后我們就可以使用它了:

php<?php$logger->pushHandler(new PDOHandler(new PDO('sqlite:logs.sqlite'));// You can now use your logger$logger->addInfo('My logger is now ready');

參考

https://github.com/Seldaek/monolog

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

See all articles