Skip to content

Adiciona tradução do PSR-3 #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
262 changes: 132 additions & 130 deletions _docs/psr/PSR-3-logger-interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,143 +7,144 @@ order: 4
Logger Interface
================

This document describes a common interface for logging libraries.

The main goal is to allow libraries to receive a `Psr\Log\LoggerInterface`
object and write logs to it in a simple and universal way. Frameworks
and CMSs that have custom needs MAY extend the interface for their own
purpose, but SHOULD remain compatible with this document. This ensures
that the third-party libraries an application uses can write to the
centralized application logs.

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
"SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
interpreted as described in [RFC 2119][].

The word `implementor` in this document is to be interpreted as someone
implementing the `LoggerInterface` in a log-related library or framework.
Users of loggers are referred to as `user`.

[RFC 2119]: http://tools.ietf.org/html/rfc2119

## 1. Specification

### 1.1 Basics

- The `LoggerInterface` exposes eight methods to write logs to the eight
[RFC 5424][] levels (debug, info, notice, warning, error, critical, alert,
emergency).

- A ninth method, `log`, accepts a log level as the first argument. Calling this
method with one of the log level constants MUST have the same result as
calling the level-specific method. Calling this method with a level not
defined by this specification MUST throw a `Psr\Log\InvalidArgumentException`
if the implementation does not know about the level. Users SHOULD NOT use a
custom level without knowing for sure the current implementation supports it.

[RFC 5424]: http://tools.ietf.org/html/rfc5424

### 1.2 Message

- Every method accepts a string as the message, or an object with a
`__toString()` method. Implementors MAY have special handling for the passed
objects. If that is not the case, implementors MUST cast it to a string.

- The message MAY contain placeholders which implementors MAY replace with
values from the context array.

Placeholder names MUST correspond to keys in the context array.

Placeholder names MUST be delimited with a single opening brace `{` and
a single closing brace `}`. There MUST NOT be any whitespace between the
delimiters and the placeholder name.

Placeholder names SHOULD be composed only of the characters `A-Z`, `a-z`,
`0-9`, underscore `_`, and period `.`. The use of other characters is
reserved for future modifications of the placeholders specification.

Implementors MAY use placeholders to implement various escaping strategies
and translate logs for display. Users SHOULD NOT pre-escape placeholder
values since they can not know in which context the data will be displayed.

The following is an example implementation of placeholder interpolation
provided for reference purposes only:
Esse documento descreve uma interface comum para registrar bibliotecas.

O objetivo principal é permitir que bibliotecas recebam um objeto
`Psr\Log\LoggerInterface` e escrevam logs para ele de maneira simples e
universal. Frameworks e CMSs que têm necessidades específicas PODEM estender
a interface para seus próprios fins, mas DEVEM-SE manter compatíveis com este
documento. Isso garante que as bibliotecas de terceiros possam escrever nos
logs da aplicação principal.

As palavras chaves "DEVE", "NÃO DEVE", "OBRIGATÓRIO", "TEM QUE", "NÃO TEM QUE",
"DEVERIA", "NÃO DEVERIA", "RECOMENDADO", "PODE", e "OPCIONAL" existentes nesse
documento devem ser interpretadas como descritas na
[RFC 2119](https://tools.ietf.org/html/rfc2119).

A palavra `implementador` deste documento é para ser interpretada como uma
implementação de `LoggerInterface` em uma biblioteca ou framework relacionados
a log. Usuários de loggers serão referidos como ` usuários `.

## 1. Especificação

### 1.1 Básico

- O `LoggerInterface` possui oito métodos para escrever logs em 8 níveis da
[RFC 5424](https://tools.ietf.org/html/rfc5424)
(debug, info, notice, warning, error, critical, alert, emergency).

- Um nono método, `log`, aceita um nível de log como primeiro argumento. Chamar
esse método com uma das constantes DEVE ter o mesmo resultado que chamar um
método de nível específico. Chamar esse método com um nível não definido por
essa especificação DEVE lançar um `Psr\Log\InvalidArgumentException` se a
implementação não conhecer o nível. Usuário NÃO DEVEM usar um nível
personalizado sem ter certeza se a implementação atual o suporta.

### 1.2 Mensagem

- Todo método aceita uma string como mensagem, ou um objeto com o método
`__toString()`. Implementadores PODEM ter um manuseio especial para os objetos
passados. Se esse não for o caso, implementadores DEVEM convertê-los para uma
string.

- A mensagem PODE conter espaços reservados (placeholders) dos quais os
implementadores PODEM substituir com valores de um array de contexto.

Os nomes dos espaços reservados DEVEM corresponder com os das chaves do array
de contexto.

Os nomes dos espaços reservados DEVEM ser limitados com uma única chave de
abertura `{` e uma única chave de fechamento `}`. NÃO DEVERÃO existir nenhum
espaço em branco entre os delimitadores e os nomes dos espaços reservados.

Nomes de espaços reservados DEVEM ser compostos apenas por caracteres
`A-Z`, `a-z`, `0-9`, sublinhado `_`, e ponto `.`. O uso de outros caracteres é
reservado para futuras modificações da especificação dos espaços reservados.

Implementadores PODEM utilizar espaços reservados para implementar várias
estratégias de saída de dados e tradução dos logs a serem exibidos. Usuários
NÃO DEVEM fazer a saída de valores dos espaços reservados antes, visto que
eles podem não saber em que contexto os dados serão exibidos.
O que segue é um exemplo de implementação de espaços reservados fornecido
apenas para fins de referência:

~~~php
<?php

/**
* Interpolates context values into the message placeholders.
* Realiza a interpolação dos valores de contexto nos espaços reservados da mensagem.
*/
function interpolate($message, array $context = array())
{
// build a replacement array with braces around the context keys
// constrói um array de substituição com chaves em torno da chave de contexto.
$replace = array();
foreach ($context as $key => $val) {
// check that the value can be casted to string
// verifica se o valor pode ser convertido para string
if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
$replace['{' . $key . '}'] = $val;
}
}

// interpolate replacement values into the message and return
// interpola os valores do array de substituição na mensagem e retorna
return strtr($message, $replace);
}

// a message with brace-delimited placeholder names
// uma mensagem com espaço reservado delimitado por chaves
$message = "User {username} created";

// a context array of placeholder names => replacement values
// um array de contexto de nomes de espaços reservados => valores de substituição
$context = array('username' => 'bolivar');

// echoes "User bolivar created"
// exibe "User bolivar created"
echo interpolate($message, $context);
~~~

### 1.3 Context
### 1.3 Contexto

- Every method accepts an array as context data. This is meant to hold any
extraneous information that does not fit well in a string. The array can
contain anything. Implementors MUST ensure they treat context data with
as much lenience as possible. A given value in the context MUST NOT throw
an exception nor raise any php error, warning or notice.
- Todo método aceita um array como dados de contexto. Isso serve para assegurar
qualquer informação estranha que não se ajuste bem a uma string. O array pode
conter qualquer coisa. Implementadores DEVEM garantir o tratamento dos dados de
contexto com a maior leniência possível. Um dado valor no contexto NÃO DEVE
lançar exceção nem, lançar qualquer erro, aviso ou notificação.

- If an `Exception` object is passed in the context data, it MUST be in the
`'exception'` key. Logging exceptions is a common pattern and this allows
implementors to extract a stack trace from the exception when the log
backend supports it. Implementors MUST still verify that the `'exception'`
key is actually an `Exception` before using it as such, as it MAY contain
anything.
- Se um objeto ` Exception ` é passado no contexto de dados, ele DEVE estar na
chave `'exception'`. As exceções de log são um padrão comum e isso permite que
implementadores extraiam uma pilha de rastreiamento da exceção quando o log de
backend suportar isto. Implementadores DEVEM ainda verificar se a chave
`'exception'` é, de fato, uma `Exception`, antes de usá-la como tal, pois esta
PODE conter qualquer coisa.

### 1.4 Helper classes and interfaces
### 1.4 Classes auxiliares e interfaces

- The `Psr\Log\AbstractLogger` class lets you implement the `LoggerInterface`
very easily by extending it and implementing the generic `log` method.
The other eight methods are forwarding the message and context to it.
- A classe `Psr\Log\AbstractLogger` permite você implementar a `LoggerInterface`
muito facilmente, estendendo-a e implementando o método de ` log ` genérico.
Os outros oito métodos encaminharão a mensagem e o contexto a ele.

- Similarly, using the `Psr\Log\LoggerTrait` only requires you to
implement the generic `log` method. Note that since traits can not implement
interfaces, in this case you still have to implement `LoggerInterface`.
- Similarmente, a utilização do `Psr\Log\LoggerTrait` requer apenas que você
implemente um método `log` genérico. Note que como traits não podem implementar
interfaces, neste caso você ainda terá que implementar a `LoggerInterface`.

- The `Psr\Log\NullLogger` is provided together with the interface. It MAY be
used by users of the interface to provide a fall-back "black hole"
implementation if no logger is given to them. However, conditional logging
may be a better approach if context data creation is expensive.
- A `Psr\Log\NullLogger` é fornecida juntamente com a interface. Ela PODE ser
usada por suários da interface para fornecer uma implementação alternativa de
"buraco negro" se nenhum logger for dado a ele. Entretanto, o log condicional
pode ser uma abordagem melhor se a criação de dados de contexto for cara.

- The `Psr\Log\LoggerAwareInterface` only contains a
`setLogger(LoggerInterface $logger)` method and can be used by frameworks to
auto-wire arbitrary instances with a logger.
- O `Psr\Log\LoggerAwareInterface` contém apenas o método
`setLogger(LoggerInterface $logger)` e pode ser utilizado por frameworks para
interligar automaticamente instâncias arbitrárias de um logger.

- The `Psr\Log\LoggerAwareTrait` trait can be used to implement the equivalent
interface easily in any class. It gives you access to `$this->logger`.
- O `Psr\Log\LoggerAwareTrait` trait pode ser utilizado para implementar a
interface equivalente tão facilmente quanto qualquer outra classe. Isso dá a
você o acesso a `$this->logger`.

- The `Psr\Log\LogLevel` class holds constants for the eight log levels.
- A classe `Psr\Log\LogLevel` mantém constantes para os oitros níveis de log.

## 2. Package
## 2. Pacote

The interfaces and classes described as well as relevant exception classes
and a test suite to verify your implementation are provided as part of the
[psr/log](https://packagist.org/packages/psr/log) package.
As interfaces e classes descritas como classes de exceção relevantes e uma
suíte de teste para verificar sua implementação são disponibilizados como parte
do pacote [psr/log](https://packagist.org/packages/psr/log).

## 3. `Psr\Log\LoggerInterface`

Expand All @@ -153,24 +154,25 @@ and a test suite to verify your implementation are provided as part of the
namespace Psr\Log;

/**
* Describes a logger instance.
* Descreve uma instância de logger
*
* The message MUST be a string or object implementing __toString().
* A mensagem DEVE ser uma string ou objeto implementando __toString().
*
* The message MAY contain placeholders in the form: {foo} where foo
* will be replaced by the context data in key "foo".
* A mensagem PODE conter espaços reservados na forma: {foo} onde foo será
* substituído pelo dado de contexto presente na chave "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".
* O array de contexto pode conter dados arbitrários, a única suposição que
* pode ser feita pelos implementadores é que se uma instância de Exception for
* dada para produzir uma pilha de rastréio, esta DEVE estar na chame nomeada
* "exception".
*
* See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
* for the full interface specification.
* Ver https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
* para a espeficicação completa da interface.
*/
interface LoggerInterface
{
/**
* System is unusable.
* Sistema está inutilizado.
*
* @param string $message
* @param array $context
Expand All @@ -179,10 +181,10 @@ interface LoggerInterface
public function emergency($message, array $context = array());

/**
* Action must be taken immediately.
* Ação deve ser tomada imediatamente.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
* Exemplo: Todo o website está fora do ar, banco de dados indisponível, etc.
* Isso deve disparar os alertas SMS e te acordar.
*
* @param string $message
* @param array $context
Expand All @@ -191,9 +193,9 @@ interface LoggerInterface
public function alert($message, array $context = array());

/**
* Critical conditions.
* Condições críticas.
*
* Example: Application component unavailable, unexpected exception.
* Exemplo: Componente da aplicação indisponível, exceção não esperada.
*
* @param string $message
* @param array $context
Expand All @@ -202,8 +204,8 @@ interface LoggerInterface
public function critical($message, array $context = array());

/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
* Erros em tempo de execução que não requerem ação imediata mas devem tipicamente
* serem registrados e monitorados.
*
* @param string $message
* @param array $context
Expand All @@ -212,10 +214,10 @@ interface LoggerInterface
public function error($message, array $context = array());

/**
* Exceptional occurrences that are not errors.
* Ocorrências excepcionais que não sejam erros.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
* Exemplo: Uso de APIs depreciadas, mal uso de uma API, coisas indesejadas
* que não necessariamente estejam erradas.
*
* @param string $message
* @param array $context
Expand All @@ -224,7 +226,7 @@ interface LoggerInterface
public function warning($message, array $context = array());

/**
* Normal but significant events.
* Eventos normais, porém insignificantes.
*
* @param string $message
* @param array $context
Expand All @@ -233,9 +235,9 @@ interface LoggerInterface
public function notice($message, array $context = array());

/**
* Interesting events.
* Eventos interessantes.
*
* Example: User logs in, SQL logs.
* Exemplo: Logins de usuários, logs de SQL.
*
* @param string $message
* @param array $context
Expand All @@ -244,7 +246,7 @@ interface LoggerInterface
public function info($message, array $context = array());

/**
* Detailed debug information.
* Informação detalhada para debug.
*
* @param string $message
* @param array $context
Expand All @@ -253,7 +255,7 @@ interface LoggerInterface
public function debug($message, array $context = array());

/**
* Logs with an arbitrary level.
* Logs com um nível arbitrário.
*
* @param mixed $level
* @param string $message
Expand All @@ -272,12 +274,12 @@ interface LoggerInterface
namespace Psr\Log;

/**
* Describes a logger-aware instance.
* Descreve uma instância de logger-aware.
*/
interface LoggerAwareInterface
{
/**
* Sets a logger instance on the object.
* Coloca uma instância de logger no objeto.
*
* @param LoggerInterface $logger
* @return void
Expand All @@ -294,7 +296,7 @@ interface LoggerAwareInterface
namespace Psr\Log;

/**
* Describes log levels.
* Descreve os níveis de log.
*/
class LogLevel
{
Expand Down