로그 메시지에 회원 아이디, ip 등 원하는 정보 추가하기

Submitted by river - 등록 10 years ago - 수정 9 years ago

Real Time Monitor

사이트를 운영하면서 오류가 발생을 하면 로그 정보에 많이 의존하게 된다. 하지만 Laravel이 기본으로 제공하는 로그 메시지로는 디버깅이 많이 불편하다. 그래서 로그 메시지에 원하는 정보를 추가할 수 있는 클래스를 하나 만들어서 사용하고 있다. 나름 만족..

MyLog.php

<?php

use Monolog\Logger;

class MyLog {

    const ERROR_IDX = 4;

    protected static $levels = array(
        'debug',
        'info',
        'notice',
        'warning',
        'error',
        'critical',
        'alert',
        'emergency',
    );

    public static function log($level, $message, $context = 'PHP') {
        $idx = array_search($level, static::$levels);

        if ($idx >= static::ERROR_IDX) {
            $count = Session::get('error_count', 0);
            Session::put('error_count', ++$count);
            if ($count > 100) return 'logged';
        }

        $data = [
            'context' => $context,
            'user_id' => Auth::check() ? Auth::user()->getKey() : 'guest',
            'url' => Input::get('url', Request::fullUrl()),
            'ip' => Request::getClientIp(),
            'count' => Session::get('error_count', 0),
            'user_agent' => get_if_set($_SERVER['HTTP_USER_AGENT'], ''),
        ];

        Log::write($level, $message, $data);
    }

    public static function __callStatic($method, $parameters) {
        if (in_array($method, static::$levels)) {
            return forward_static_call_array(array('MyLog', 'log'), array_merge(array($method), $parameters));
        }
        throw new \BadMethodCallException("Method [$method] does not exist.");
    }
}

helpers.php

<?php

/**
 * 변수가 설정되어 있으면 그 값을 반환하고, 그렇지 않으면 value(default는 null)를 반환한다.
 *
 * @param $var
 * @param null $value
 * @return null
 */
function get_if_set(&$var, $value = null) {
    if (isset($var)) {
        return $var;
    }
    return $value;
}

사용예제

filters.php

App::missing(function($exception)
{
    MyLog::warning('404 ' . Request::fullUrl() . ", method=" . Request::method() );
    return Response::view('errors.404', array(), 404);
});

필터를 이용, 404 page not found 발생 시 로그를 남기고, 이 로그에 회원 아이디, ip 정보 등이 추가로 저장된다.

관련글

comments powered by Disqus