简体   繁体   中英

Custom monolog in order to perform extra actions

Helo people,

In my project, sometimes I need to send emails and log messages. The thing is that I'm not using swift mailer, I'm using an API that takes care of sending emails for me.

The solution I've tried is that I created a custom processor where I injected my client mailer. I've followed http://symfony.com/doc/current/cookbook/logging/monolog.html#adding-a-session-request-token .

So I have something like the following:

namespace Tools\LoggerBundle;

use Symfony\Component\HttpFoundation\Session\Session;

class CustomProcessor
{
    private $session;
    private $token;
    // Client Mailer
    private $mailer;

    public function __construct(Session $session, $mailer)
    {
        $this->session = $session;
        $this->mailer = $mailer;
    }

    public function processRecord(array $record)
    {
        if (null === $this->token) {
            try {
                $this->token = substr($this->session->getId(), 0, 8);
            } catch (\RuntimeException $e) {
                $this->token = '????????';
            }
            $this->token .= '-' . substr(uniqid(), -8);
        }
        $record['extra']['token'] = $this->token;

        // Sends an email    
        $this->mailer->send('Alert', print_r($record, true));

        return $record;
    }
}

This works pretty well, except I need to send emails only when level is greater than warning. At the same time, normal logging shouldn't stop.

What do you suggest?

You should use class Handler for email sending instead of doing it on processoser

<?php

use Monolog\Handler\AbstractProcessingHandler;

class EmailHandler extends AbstractProcessingHandler
{
    private $mailer;

    public function __construct($mailer, $level = Logger::WARNING, $bubble = true)
    {
        parent::__construct($level, $bubble);
        $this->mailer = $mailer;
    }

    protected function write(array $record)
    {
        $this->mailer->send($record['level_name'], print_r($record, true));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM