Upload
interfanallin
View
218
Download
0
Embed Size (px)
Citation preview
7/25/2019 PSR 3_Logger Interface PHP FIG
1/10
PHP-FIGHomeRecommendations (PSRs)MembersBylawsFAQsGet InvolvedPSR-3: LoggerInterfacePSR-3: LoggerInterface
Thisdocument describesa common interface forlogging libraries.
The main goal isto allowlibrariesto receive a Psr\Log\LoggerInterface object
andwrite logsto it in a simple anduniversal way. FrameworksandCMSsthat
have custom needsMAY extendthe interface fortheirown purpose, but
SHOULD remain compatible with thisdocument. Thisensuresthat the
third-party librariesan application usescan write to the centralized
application logs.
The key words"MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and"OPTIONAL" in
thisdocument are to be interpretedasdescribedin RFC 2119.
The word implementor in thisdocument isto be interpretedassomeone
implementing the LoggerInterface in a log-relatedlibrary orframework.
Usersof loggersare referredto as user .
1. Speci cation
1.1Basics
The LoggerInterface exposeseight methodsto write logsto the eight RFC
5424levels(debug, info, notice, warning, error, critical, alert, emergency).
A ninth method, log , acceptsa log level asfirst argument. Calling this
3: Logger Interface - PHP-FIG http://www.php-fig.org/p
0 19/06/2016 0
7/25/2019 PSR 3_Logger Interface PHP FIG
2/10
methodwith one of the log level constantsMUST have the same result as
calling the level-specific method. Calling thismethodwith a level not
definedby thisspecification MUST throwa Psr\Log
\InvalidArgumentException if the implementation doesnot knowabout the
level. UsersSHOULD NOT use a custom level without knowing forsure the
current implementation supportsit.
1.2Message
Every methodacceptsa string asthe message, oran object with a
__toString() method. ImplementorsMAY have special handling forthe
passedobjects. If that isnot the case, implementorsMUST cast it to a
string.
The message MAY contain placeholderswhich implementorsMAY replace
with valuesfrom the context array.
PlaceholdernamesMUST correspondto keysin the context array.
PlaceholdernamesMUST be delimitedwith a single opening brace { anda
single closing brace } . There MUST NOT be any whitespace between the
delimitersandthe placeholdername.
PlaceholdernamesSHOULD be composedonly of the characters A-Z , a-z ,
0-9 , underscore _ , andperiod . . The use of othercharactersisreservedfor
future modificationsof the placeholdersspecification.
ImplementorsMAY use placeholdersto implement variousescaping
strategiesandtranslate logsfordisplay. UsersSHOULD NOT pre-escape
placeholdervaluessince they can not knowin which context the data will be
displayed.
The following isan example implementation of placeholderinterpolation
3: Logger Interface - PHP-FIG http://www.php-fig.org/p
0 19/06/2016 0
7/25/2019 PSR 3_Logger Interface PHP FIG
3/10
providedforreference purposesonly:
/**
* Interpolates context values into the message placeholders.
*/
function interpolate($message, array $context = array())
{
// build a replacement array with braces around the context keys
$replace = array();
foreach ($context as $key => $val) {
$replace['{' . $key . '}'] = $val;
}
// interpolate replacement values into the message and return
return strtr($message, $replace);
}
// a message with brace-delimited placeholder names
$message = "User {username} created";
// a context array of placeholder names => replacement values
$context = array('username' => 'bolivar');
// echoes "User bolivar created"
echo interpolate($message, $context);
1.3Context
Every methodacceptsan array ascontext data. Thisismeant to holdany
extraneousinformation that doesnot fit well in a string. The array can
contain anything. ImplementorsMUST ensure they treat context data with
asmuch lenience aspossible. A given value in the context MUST NOT
throwan exception norraise any php error, warning ornotice.
3: Logger Interface - PHP-FIG http://www.php-fig.org/p
0 19/06/2016 0
7/25/2019 PSR 3_Logger Interface PHP FIG
4/10
If an Exception object ispassedin the context data, it MUST be in the
'exception' key. Logging exceptionsisa common pattern andthisallows
implementorsto extract a stack trace from the exception when the log
backendsupportsit. ImplementorsMUST still verify that the 'exception'
key isactually an Exception before using it assuch, asit MAY contain
anything.
1.4 Helperclassesandinterfaces
The Psr\Log\AbstractLogger classletsyouimplement the LoggerInterface
very easily by extending it andimplementing the generic log method.
The othereight methodsare forwarding the message andcontext to it.
Similarly, using the Psr\Log\LoggerTrait only requiresyouto implement
the generic log method. Note that since traitscan not implement
interfaces, in thiscase youstill have to implement LoggerInterface .
The Psr\Log\NullLogger isprovidedtogetherwith the interface. It MAY be
usedby usersof the interface to provide a fall-back "black hole"
implementation if no loggerisgiven to them. Howeverconditional logging
may be a betterapproach if context data creation isexpensive.
The Psr\Log\LoggerAwareInterface only containsa
setLogger(LoggerInterface $logger) methodandcan be usedby
frameworksto auto-wire arbitrary instanceswith a logger.
The Psr\Log\LoggerAwareTrait trait can be usedto implement the
equivalent interface easily in any class. It givesyouaccessto
$this->logger .
The Psr\Log\LogLevel classholdsconstantsforthe eight log levels.
2. Package
The interfacesandclassesdescribedaswell asrelevant exception classes
3: Logger Interface - PHP-FIG http://www.php-fig.org/p
0 19/06/2016 0
7/25/2019 PSR 3_Logger Interface PHP FIG
5/10
anda test suite to verify yourimplementation isprovidedaspart of the
psr/logpackage.
3. Psr\Log\LoggerInterface
7/25/2019 PSR 3_Logger Interface PHP FIG
6/10
publicfunctioneme gency($message, a ay$context=a ay());
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This shoul * trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
* @return null
*/
publicfunctionale t($message, a ay$context=a ay());
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context * @return null
*/
publicfunctionc itical($message, a ay$context=a ay());
/**
* Runtime errors that do not require immediate action but should typi
* be logged and monitored.
*
* @param string $message
* @param array $context
* @return null
*/
public
function
e o
($message,a ay
$context=
a ay
());
3: Logger Interface - PHP-FIG http://www.php-fig.org/p
0 19/06/2016 0
7/25/2019 PSR 3_Logger Interface PHP FIG
7/10
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable thi
* that are not necessarily wrong.
* * @param string $message
* @param array $context
* @return null
*/
publicfunctionwa ning($message, a ay$context=a ay());
/**
* Normal but significant events.
*
* @param string $message
* @param array $context
* @return null
*/
publicfunctionnotice($message, a ay$context=a ay());
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
* @return null
*/
publicfunctioninfo($message, a ay$context=a ay());
/**
* Detailed debug information.
*
3: Logger Interface - PHP-FIG http://www.php-fig.org/p
0 19/06/2016 0
7/25/2019 PSR 3_Logger Interface PHP FIG
8/10
* @param string $message
* @param array $context
* @return null
*/
publicfunctiondebug($message, a ay$context=a ay());
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
* @return null
*/
publicfunctionlog($level, $message, a ay$context=a ay());
}
4. Psr\Log\LoggerAwareInterface
7/25/2019 PSR 3_Logger Interface PHP FIG
9/10
*/
publicfunction etLogge (LoggerInterface $logger);
}
5. Psr\Log\LogLevel
7/25/2019 PSR 3_Logger Interface PHP FIG
10/10
Followuson Twitter Chat on IRC Channel Contribute via Github Join ourmailing list
2016PHP Framework Interop Group. Site design by Jonathan Reinink.
3: Logger Interface - PHP-FIG http://www.php-fig.org/p