日志级别
debug, info, notice, warning, error, critical, alert, emergency
其中有一个特别的级别:sql,专门用来记录sql语句的
设置日志记录级别
对于程序比较重要的业务模块可以进行埋点(进行日志记录)
可以通过设置日志记录级别来开启和关闭记录
有助于排除错误(比每次出现错误去代码里增加记录日志好多了)
# 修改 config/log.php # 配置 'level' => ['notice','warning'] # level 不为空时,只记录level中指定的错误级别 # level 为空时,记录所有级别 $user = UserService::getInstance()->findByUsername('xieruixiang'); Log::warning("warning:{user}", compact('user')); # info 不再 level 中 则不会记录 Log::info("I'm info");
默认的tp日志是写在当前日期(年月)目录下的,如(runtime/admin/log/202204/30_info.log)
单一日志设置 修改config/log.php 中通道single属性为true
设置单一日志后,将不再写在时间目录下(一直写一个固定目录),如(runtime/admin/log/single_info.log)
# 开启单一日志 # channels.file.single # 这里给file通道开启单一日志 'single' => true
独立日志
每一种日志级别的日志都归类到一个文件之中(推荐开启独立日志)
设置 config/log.php 中通道apart_level属性
# 设置 file 通道 info,notice,warning 级别开启独立日志
# channels.file.apart_level
# ‘apart_level’ => [‘info’, ‘notice’, ‘warning’]
# 在 apart_level中的级别会独立写到一个文件中去
# write to runtime/admin/log/202204/30_warning.log
Log::warning(“I’m “);
# write to runtime/admin/log/202204/30_info.log
Log::info(“I’m info”);
# write to runtime/admin/log/202204/30_notice.log
Log::notice(“I’m notice”);
日志的写入时机
日志写入时机提供两种(实时写入,程序执行完后写入)
通过设置config/log.php中通道 realtime_write 属性
# 这里中断程序的执行
# 如果 realtime_write = false 则无法写到日志中去
# realtime_write = true 可以写入日志中去
Log::warning(“I’m “);
# 如果 realtime_write = false
# 又想实时写入
# 可以通过 Log::write($msg, $type) 实时写入
# $msg 信息
# $type 日志级别
Log::write(“I’m write”, ‘warning’);
die(“日志将不会写入”);
日志通道
可以自定义通道
以增加邮件通道为例
将config/log.php 中通道type 改成自定义驱动类即可
# config/log.php channels 添加 'email' => [ 'type' => \app\admin\driver\EmailDriver::class, # 调试发送邮件时将其设置成实时比较好调试 'realtime_write' => true, ] # EmailDriver 需要实现 think\contract\LogHandlerInterface class EmailDriver implements LogHandlerInterface { public function save(array $log): bool { # 这里进行发送邮件逻辑 # 想知道邮件发送逻辑的可以参考我的文章 《php发送邮件》 # 不想知道的 可以调用第三方封装好的php发送邮件组件 return true; } }
# channel($channelName) 指定发送通道 # 不指定则使用默认发送通道 # config/log.php # 'default' => env('log.channel', 'file'), Log::channel('email')->info("this is info"); # 就能以邮件形式通知了