PSR-3: 로거 인터페이스

Jmnote (토론 | 기여)님의 2021년 7월 22일 (목) 01:06 판 (→‎기본)

1 개요

PSR-3: Logger Interface
PSR-3: 로거 인터페이스

이 문서는 로깅 라이브러리를 위한 공통 인터페이스를 설명한다.

주요 목표는 라이브러리가 Psr\Log\LoggerInterface 객체를 받고 간단하고 보편적인 방식으로 로그를 작성할 수 있도록 하는 것이다. 사용자 정의 요구사항이 있는 프레임워크 및 CMS는 자체 목적을 위해 인터페이스를 확장할 수 있지만(MAY), 이 문서와 계속 호환되어야 한다(SHOULD). 이렇게 하면 애플리케이션에서 사용하는 타사 라이브러리가 중앙집중식 애플리케이션 로그에 쓸 수 있다.

이 문서의 키워드 "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", "OPTIONAL"은 RFC 2119에 설명된 대로 해석된다.

이 문서에서 구현자(implementor)라는 단어는 로그 관련 라이브러리나 프레임워크에서 LoggerInterface를 구현하는 사람으로 해석된다. 로거의 사용자는 사용자(user)라고 한다.

2 사양

2.1 기본

  • LoggerInterface는 8개의 RFC 5424 수준(디버그, 정보, 알림, 경고, 오류, 위험, 경고, 비상)으로 로그를 기록하는 8가지 메소드를 제공한다.
  • 9번째 메소드인 log는 첫 번째 인수로 로그 수준을 받는다. 로그 수준 상수 중 하나로 이 메서드를 호출하는 것은 수준별 메소드를 호출하는 것과 동일한 결과가 되어야 한다(MUST). 이 사양에 정의되지 않은 수준으로 이 메서드를 호출하면, 구현체에서 수준에 대해 알지 못하는 경우 Psr\Log\InvalidArgumentException을 throw해야 합니다(MUST). 사용자는 현재 구현체가 지원하는지 확인하지 않은 채, 사용자 정의 수준을 사용해서는 안 된다(SHOULD NOT).

2.2 메시지

2.3 컨텍스트

  • 모든 메서드는 배열을 컨텍스트 데이터로 받아들인다. 이것은 문자열에 잘 맞지 않는 관련 없는 정보를 보유하기 위한 것이다. 배열은 무엇이든 포함할 수 있다. 구현자는 컨텍스트 데이터를 가능한 한 관대하게 처리해야 한다(MUST). 컨텍스트의 주어진 값은 예외를 발생시키거나 PHP 오류, 경고, 알림을 발생시키지 않아야 한다(MUST NOT).
  • Exception 객체가 컨텍스트 데이터로 전달되면 'exeception' 키에 있어야 한다. 예외 로깅은 일반적인 패턴이며 이를 통해 구현자는 로그 백엔드가 지원할 때 예외에서 스택 추적을 추출할 수 있다. 다만 'exeception' 키에는 무엇이든 들어갈 수 있으므로, 구현자는 이를 그대로 사용하기 말고 'exeception' 키가 실제로 Exception인지 확인해야 한다(MUST).

2.4 헬퍼 클래스와 인터페이스

  • Psr\Log\AbstractLogger 클래스를 사용하면 LoggerInterface를 매우 쉽게 확장·구현하고 제네릭 log 메소드를 구현할 수 있다. 다른 8가지 방법은 메시지와 컨텍스트를 전달하는 것이다.
  • 비슷하게, Psr\Log\LoggerTrait를 사용하려면 제네릭 log 메소드만 구현하면 된다. 특성(trait)은 인터페이스를 구현할 수 없으므로 이 경우 여전히 LoggerInterface를 구현해야 한다.
  • Psr\Log\NullLogger는 인터페이스와 함께 제공된다. 로거가 제공되지 않는 경우 인터페이스 사용자가 폴백(fall-back) "블랙홀" 구현을 제공하는 데 사용할 수 있다(MAY). 그러나 컨텍스트 데이터 생성에 비용이 많이 든다면 조건부 로깅이 더 나은 접근 방식일 수 있다.
  • Psr\Log\LoggerAwareInterfacesetLogger(LoggerInterface $logger) 메소드만 가지며 프레임워크에서 로거와 임의의 인스턴스를 자동 연결하는 데 사용할 수 있다.
  • Psr\Log\LoggerAwareTrait 특성은 모든 클래스에서 동등한 인터페이스를 쉽게 구현하는 데 사용할 수 있다. $this->logger에 대한 액세스를 제공한다.
  • Psr\Log\LogLevel 클래스는 8개가지 로그 수준에 대한 상수를 가진다.

3 패키지

  • 설명된 인터페이스 및 클래스는 물론, 구현을 검증하기 위한 관련 예외 클래스 및 테스트 제품군이 psr/log 패키지의 일부로 제공된다.

4 Psr\Log\LoggerInterface

?php

namespace Psr\Log;

/**
 * Describes a logger instance.
 *
 * 메시지는 문자열 또는 __toString()이 구현된 객체여야 한다(MUST).
 *
 * The message MAY contain placeholders in the form: {foo} where foo
 * will be replaced by the context data in key "foo".
 *
 * The context array can contain arbitrary data, the only assumption that
 * can be made by implementors is that if an Exception instance is given
 * to produce a stack trace, it MUST be in a key named "exception".
 *
 * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
 * for the full interface specification.
 */
interface LoggerInterface
{
    /**
     * System is unusable.
     *
     * @param string $message
     * @param array $context
     * @return void
     */
    public function emergency($message, array $context = array());

    /**
     * Action must be taken immediately.
     *
     * Example: Entire website down, database unavailable, etc. This should
     * trigger the SMS alerts and wake you up.
     *
     * @param string $message
     * @param array $context
     * @return void
     */
    public function alert($message, array $context = array());

    /**
     * Critical conditions.
     *
     * Example: Application component unavailable, unexpected exception.
     *
     * @param string $message
     * @param array $context
     * @return void
     */
    public function critical($message, array $context = array());

    /**
     * Runtime errors that do not require immediate action but should typically
     * be logged and monitored.
     *
     * @param string $message
     * @param array $context
     * @return void
     */
    public function error($message, array $context = array());

    /**
     * Exceptional occurrences that are not errors.
     *
     * Example: Use of deprecated APIs, poor use of an API, undesirable things
     * that are not necessarily wrong.
     *
     * @param string $message
     * @param array $context
     * @return void
     */
    public function warning($message, array $context = array());

    /**
     * Normal but significant events.
     *
     * @param string $message
     * @param array $context
     * @return void
     */
    public function notice($message, array $context = array());

    /**
     * Interesting events.
     *
     * Example: User logs in, SQL logs.
     *
     * @param string $message
     * @param array $context
     * @return void
     */
    public function info($message, array $context = array());

    /**
     * Detailed debug information.
     *
     * @param string $message
     * @param array $context
     * @return void
     */
    public function debug($message, array $context = array());

    /**
     * Logs with an arbitrary level.
     *
     * @param mixed $level
     * @param string $message
     * @param array $context
     * @return void
     */
    public function log($level, $message, array $context = array());
}

5 Psr\Log\LoggerAwareInterface

<?php

namespace Psr\Log;

/**
 * Describes a logger-aware instance.
 */
interface LoggerAwareInterface
{
    /**
     * 객체에서 로거 인스턴스를 설정한다
     *
     * @param LoggerInterface $logger
     * @return void
     */
    public function setLogger(LoggerInterface $logger);
}

6 Psr\Log\LogLevel

<?php

namespace Psr\Log;

/**
 * Describes log levels.
 */
class LogLevel
{
    const EMERGENCY = 'emergency';
    const ALERT     = 'alert';
    const CRITICAL  = 'critical';
    const ERROR     = 'error';
    const WARNING   = 'warning';
    const NOTICE    = 'notice';
    const INFO      = 'info';
    const DEBUG     = 'debug';
}

7 같이 보기

8 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}