Logger¶
Instantiation¶
New in version 11.4: Feature: #95044 - Support autowired LoggerInterface injection
Constructor injection can be used to automatically instantiate the logger:
use Psr\Log\LoggerInterface;
class MyClass {
private LoggerInterface $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
}
Tip
For examples of instantiation with LoggerAwareTrait
or
GeneralUtility::makeInstance()
, switch to an older TYPO3 version for this
page. Instantiation with dependency injection is now the recommended
procedure. Also see the section on channels for
information on grouping classes in channels.
Log levels and shorthand methods¶
Log levels according to RFC 3164, starting from the lowest level.
For each of the severity levels mentioned above, a shorthand method exists in
\TYPO3\CMS\Core\Log\Logger
, like
- Debug
| debug information |
\TYPO3\CMS\Core\Log\LogLevel::DEBUG
|$this->logger->debug($message, array $context = array());
|Detailed status information during the development of new PHP code.
- Informational
| informational messages |
\TYPO3\CMS\Core\Log\LogLevel::INFO
|$this->logger->info($message, array $context = array());
|User logs in, SQL logs.
- Notice
| significant condition |
\TYPO3\CMS\Core\Log\LogLevel::NOTICE
|$this->logger->notice($message, array $context = array());
|Things you should have a look at, nothing to worry about though. Example: User log ins, SQL logs.
- Warning
| warning condition |
\TYPO3\CMS\Core\Log\LogLevel::WARNING
|$this->logger->warning($message, array $context = array());
|Use of deprecated APIs. Undesirable events that are not necessarily wrong. Example: Use of a deprecated method.
- Error
| error condition |
\TYPO3\CMS\Core\Log\LogLevel::ERROR
|$this->logger->error($message, array $context = array());
|Runtime error. Some PHP coding error has happened. A white screen is shown.
- Critical
| critical condition |
\TYPO3\CMS\Core\Log\LogLevel::CRITICAL
|$this->logger->critical($message, array $context = array());
|Unexpected exception. An important file has not been found, data is corrupt or outdated.
- Alert
| blocking condition |
\TYPO3\CMS\Core\Log\LogLevel::ALERT
|$this->logger->alert($message, array $context = array());
|Action must be taken immediately. Entire website down, database unavailable.
- Emergency
| nothing works |
\TYPO3\CMS\Core\Log\LogLevel::EMERGENCY
|$this->logger->emergency($message, array $context = array());
|The system is unusable. You will likely not be able to reach the system. You better have a system admin reachable when this happens.
log() Method¶
\TYPO3\CMS\Core\Log\Logger
provides a central point for submitting log messages,
the log()
method:
$this->logger->log($level, $message, $data);
which takes three parameters:
Parameter |
Type |
Description |
---|---|---|
$level |
Type integer |
See the chapter above. |
$message |
Type string |
The log message itself. |
$data |
Type array |
Optional parameter, can contain additional data, which is added to the log record in the form of an array. |
An early return in the log()
method prevents unneeded computation work to be done.
So you are safe to call $this->logger->debug()
frequently without slowing down your code too much.
The Logger will know by its configuration, what the most explicit severity level is.
As next step, all registered Processors are notified. They can modify the log records or add extra information.
The Logger then forwards the log records to all of its configured Writers, which will then persist the log record.
Channels¶
It is possible to group several classes into channels, regardless of the PHP namespace.
Services are able to control the component name that an injected logger is created with. This allows to group logs of related classes and is basically a channel system as often used in monolog.
The TYPO3\CMS\Core\Log\Channel
attribute is supported for constructor
argument injection as a class and parameter specific attribute and for
LoggerAwareInterface
dependency injection services as a class attribute.
This feature is only available with PHP 8. The channel attribute will be gracefully ignored in PHP 7, and the classic component name will be used instead.
Registration via class attribute for LoggerInterface
injection:
namespace MyVendor\MyExtension\Service\MyClass;
use Psr\Log\LoggerInterface;
use TYPO3\CMS\Core\Log\Channel;
#[Channel('security')]
class MyClass
{
private LoggerInterface $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
// do your magic
}
}
Registration via parameter attribute for LoggerInterface
injection, overwrites possible class attributes:
namespace MyVendor\MyExtension\Service\MyClass;
use Psr\Log\LoggerInterface;
use TYPO3\CMS\Core\Log\Channel;
class MyClass
{
private LoggerInterface $logger;
public function __construct(
#[Channel('security')]
LoggerInterface $logger
) {
$this->logger = $logger;
// do your magic
}
}
The instantiated logger will now have the channel "security",
instead of the default which would be a combination of namespace and class of
the instantiating class, such as MyVendor.MyExtension.Service.MyClass
.
Using the Channel¶
The channel "security" can then be used in the logging configuration:
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Log\LogLevel;
use TYPO3\CMS\Core\Log\Writer\FileWriter;
$GLOBALS['TYPO3_CONF_VARS']['LOG']
['security']
['writerConfiguration'] = [
LogLevel::DEBUG => [
FileWriter::class => [
'logFile' => Environment::getVarPath() . '/log/security.log'
]
],
];
The written log messages will then have the component name "security"
, such as:
Fri, 21 Oct 2022 16:26:13 +0000 [DEBUG] ... component="security": ...
For more examples for configuring the logging see Writer configuration.
Examples¶
Examples of the usage of the Logger can be found in the extension
EXT:examples. in file
/Classes/Controller/ModuleController.php
Best practices¶
There are no strict rules or guidelines about logging. Still it can be considered to be best practice to follow these rules:
Use placeholders¶
Adhere to the PSR-3 placeholder specification. This is necessary in order to use proper PSR-3 Logging.
Bad example:
// $this->logger->alert(
'Password reset requested for email "' .
$emailAddress . '" . but was requested too many times.');
Good example:
$this->logger->alert(
'Password reset requested for email {email} but was requested too many times.',
['email' => $emailAddress]);
The first argument is 'message', second (optional) argument is 'context'.
A message can use {placeholders}
. All Core provided log writers will
substitute placeholders in the message with data from the context array,
if a context array key with same name exists.
Meaningful message¶
The message itself has to be meaningful, for example exception messages.
Bad example:
"Something went wrong"
Good example:
"Could not connect to database"
Searchable message¶
Most of the times log entries will be stored. They are most important if something goes wrong within the system. In such situations people might search for specific issues or situations, considering this while writing log entries will reduce debugging time in future.
Messages should therefore contain keywords that might be used in searches.
Good example:
"Connection to mysql database could not be established"
This includes "connection", "mysql" and "database" as possible keywords.
Distinguishable and grouped¶
Log entries might be collected and people might scroll through them. Therefore it is helpful to write log entries that are distinguishable, but are also grouped.
Bad examples:
"Connection to mysql database could not be established."
"Could not establish connection to memcache."
Good examples:
"Connection to mysql database could not be established."
"Connection to memcache could not be established."
This way the same issue is grouped by the same structure, and one can scan the same position for either "mysql" or "memcache".
Provide useful information¶
TYPO3 already uses the component of the logger to give some context. Still further individual context might be available that should be added. In case of an exception, the code, stacktrace, file and line number would be helpful.
Keep in mind that it is hard to add information afterwards. Logging is there to get information if something got wrong. All necessary information should be available to get the state of the system and why something happened.