laravel中的日志是基于monolog而封装的。laravel在它上面作了几个事情:php
好了,看下下面几个需求怎么实现:laravel
这个需求很广泛的,好比调用订单的日志,须要记录到order.log,获取店铺信息的记录须要记录到shop.log中去。能够这么作:git
<?php use Monolog\Logger; use Monolog\Handler\StreamHandler; use Illuminate\Log\Writer; class BLogger { // 全部的LOG都要求在这里注册 const LOG_ERROR = 'error'; private static $loggers = array(); // 获取一个实例 public static function getLogger($type = self::LOG_ERROR, $day = 30) { if (empty(self::$loggers[$type])) { self::$loggers[$type] = new Writer(new Logger($type)); self::$loggers[$type]->useDailyFiles(storage_path().'/logs/'. $type .'.log', $day); } $log = self::$loggers[$type]; return $log; } }
这样不一样的日志数据会被存储到不一样的日志文件中去。还能记录日志数据信息。github
使用上面的BLogger类,在start/global.php记录下必要的错误信息sql
// 错误日志信息 App::error(function(Exception $exception, $code) { Log::error($exception); $err = [ 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'code' => $exception->getCode(), 'url' => Request::url(), 'input' => Input::all(), ]; BLogger::getLogger(BLogger::LOG_ERROR)->error($err); });
因此应该默认把laravel的默认日志记录改为有分割的。数据库
一样在start/global.php中json
Log::useDailyFiles(storage_path().'/logs/laravel.log', 30);
这个应该再细化问,你是否是要实时记录?服务器
若是不要实时记录,那么laravel有个DB::getQueryLog能够获取一个app请求获取出来的sql请求:app
## 在filters.php中 App::after(function($request, $response) { // 数据库查询进行日志 $queries = DB::getQueryLog(); if (Config::get('query.log', false)) { BLogger::getLogger('query')->info($queries); } }
若是你是须要实时记录的(也就是你在任何地方die出来的时候,以前的页面的sql请求也有记录)的话,你就须要监听illuminate.query事件了函数
// 数据库实时请求的日志 if (Config::get('database.log', false)) { Event::listen('illuminate.query', function($query, $bindings, $time, $name) { $data = compact('query','bindings', 'time', 'name'); BLogger::getLogger(BLogger::LOG_QUERY_REAL_TIME)->info($data); }); }
laravel的全部错误会所有过global的App::error再出来
因此好比你设计的是接口,但愿即便有error出现也返回json数据,则能够这么作:
// 错误日志信息 App::error(function(Exception $exception, $code) { // 若是没有路径就直接跳转到登陆页面 if ($exception instanceof NotFoundHttpException) { return Redirect::route('login'); } Log::error($exception); $err = [ 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'code' => $exception->getCode(), 'url' => Request::url(), 'input' => Input::all(), ]; BLogger::getLogger(BLogger::LOG_ERROR)->error($err); $response = [ 'status' => 0, 'error' => "服务器内部错误", ]; return Response::json($response); });
若是你还但愿将404错误也hold住:
App::missing(function($exception) { $response = [ 'status' => 0, 'error' => "请求路径错误", ]; return Response::json($response); });