官术网_书友最值得收藏!

Our own logger

Now that we have a channel for our module, let's assume that we also want to log messages elsewhere. They are fine to be stored in the database, but let's also send an email whenever we encounter an error log. In this section, we will only cover the logging architecture needed for this and defer the actual mailing implementation to the second part of this chapter when we discuss mailing.

The first thing that we will need to create is the LoggerInterface implementation, which typically goes in the Logger folder of our namespace. So, let's call ours MailLogger. And it can look like this:

namespace Drupal\hello_world\Logger;

use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;

/**
* A logger that sends an email when the log type is "error".
*/
class MailLogger implements LoggerInterface {

use RfcLoggerTrait;

/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array()) {
// Log our message to the logging system.
}
}

The first thing to note is that we are implementing the PSR-3 LoggerInterface. This will require a bunch of methods, but we will take care of most of them via RfcLoggerTrait. The only one left to implement is the log() method, which will be responsible for doing the actual logging. For now, we will keep it empty.

By itself, having this class does nothing. We will need to register it as a tagged service so that LoggingChannelFactory picks it up and passes it to the logging channel when something needs to be logged. Let's take a look at what that definition looks like:

hello_world.logger.hello_world:
class: Drupal\hello_world\Logger\MailLogger
tags:
- { name: logger }

As it stands, our logger doesn't need any dependencies. However, note the property called tags with which we tag this service with the logger tag. This will register it as a specific service that another service (called a collector) looks for. Just like we discussed in the previous chapter. In this case, the collector is LoggingChannelFactory.

Clearing the cache should enable our logger. This means that when a message is being logged, via any channel, our logger is also used, together with any other enabled loggers (by default, the database one). So, if we want our logger to be the only one, we will need to disable the DB Log module from Drupal core.

We will continue working on this class later in this chapter when we will cover sending out emails programmatically.

主站蜘蛛池模板: 青岛市| 淮安市| 武冈市| 卢氏县| 元朗区| 合江县| 左贡县| 响水县| 竹溪县| 卓尼县| 东海县| 武义县| 凯里市| 阳新县| 比如县| 东乡族自治县| 铜山县| 泸定县| 泸溪县| 博爱县| 彭泽县| 兴安县| 松潘县| 通城县| 西华县| 云霄县| 曲阜市| 高淳县| 自治县| 阳谷县| 墨玉县| 安岳县| 商丘市| 宣化县| 广南县| 泰来县| 丹寨县| 徐水县| 宜城市| 香港| 罗定市|