Skip to content

Commit

Permalink
Added ability to pass SwiftMailer log entries to Yii::info()
Browse files Browse the repository at this point in the history
  • Loading branch information
klimov-paul committed Mar 25, 2015
1 parent e204c99 commit d30d730
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 2 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Expand Up @@ -4,7 +4,7 @@ Yii Framework 2 swiftmailer extension Change Log
2.0.4 under development
-----------------------

- no changes in this release.
- Enh #4: Added ability to pass SwiftMailer log entries to `Yii::info()` (klimov-paul)


2.0.3 March 01, 2015
Expand Down
58 changes: 58 additions & 0 deletions Logger.php
@@ -0,0 +1,58 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/

namespace yii\swiftmailer;

use Yii;

/**
* Logger is as SwiftMailer plugin, which allows passing of the SwiftMailer internal logs to the
* Yii logging mechanism. Each native SwiftMailer log message will be converted into Yii 'info' log entry.
*
* In order to catch logs written by this class, you need to setup a log route for 'yii\swiftmailer\Logger::add' category.
* For example:
*
* ~~~
* 'log' => [
* 'targets' => [
* [
* 'class' => 'yii\log\FileTarget',
* 'categories' => ['yii\swiftmailer\Logger::add'],
* ],
* ],
* ],
* ~~~
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0
*/
class Logger implements \Swift_Plugins_Logger
{
/**
* @inheritdoc
*/
public function add($entry)
{
Yii::info($entry, __METHOD__);
}

/**
* @inheritdoc
*/
public function clear()
{
// empty method stub
}

/**
* @inheritdoc
*/
public function dump()
{
return '';
}
}
22 changes: 21 additions & 1 deletion Mailer.php
Expand Up @@ -79,6 +79,12 @@ class Mailer extends BaseMailer
* @var string message default class name.
*/
public $messageClass = 'yii\swiftmailer\Message';
/**
* @var boolean whether to enable writing of the SwiftMailer internal logs using Yii log mechanism.
* If enabled [[Logger]] plugin will be attached to the [[transport]] for this purpose.
* @see Logger
*/
public $enableSwiftMailerLogging = false;

/**
* @var \Swift_Mailer Swift mailer instance.
Expand Down Expand Up @@ -163,10 +169,24 @@ protected function createTransport(array $config)
if (isset($config['plugins'])) {
$plugins = $config['plugins'];
unset($config['plugins']);
} else {
$plugins = [];
}

if ($this->enableSwiftMailerLogging) {
$plugins[] = [
'class' => 'Swift_Plugins_LoggerPlugin',
'constructArgs' => [
[
'class' => 'yii\swiftmailer\Logger'
]
],
];
}

/* @var $transport \Swift_MailTransport */
$transport = $this->createSwiftObject($config);
if (isset($plugins)) {
if (!empty($plugins)) {
foreach ($plugins as $plugin) {
if (is_array($plugin) && isset($plugin['class'])) {
$plugin = $this->createSwiftObject($plugin);
Expand Down

0 comments on commit d30d730

Please sign in to comment.