I've heard a lot about monolog(https://github.com/Seldaek/monolog) & trying to use that in one of our app. But, can't able to fig. out how to use that. Don't know it's I'm only can't able to get any documentation of it or really it has no documentation at all.
We want to log all our errors in DB & as well as send an email notification about error when it'll get generate. For sending email we are using Swiftmailer(swiftmailer.org).
I can be able to run this sample code from Github link,
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));
// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');
but can't able to understand how to use this with DB & any other email library.
You posted an example yourself. Instead of StreamHandler use one or more of the other handlers that monolog is offering.
You have to look into the code of the handlers to see which dependencies they need. Look inside the Monolog directory and you'll find the Handler classes. Code is the most reliable documentation.
<?php
use Monolog\Logger;
use Monolog\Handler\SwiftMailerHandler;
use Swift_Mailer;
// ... more dependencies you need
// create your Swift_Mailer and Swift_Message instances
$handlers = [
new SwiftMailerHandler($swiftMailer, $swiftMessage),
// add more handler you need
];
$log = new Logger('name', $handlers);
$log->warning('Foo');
$log->error('Bar');
You have to create a Swift_Mailer and Swift_Message instance for the SwiftMailerHandler. Instead of pushHandler, you can add an array of handlers into the Logger constructor.
The Swift_Message instance is used for every log message where the message replaces every time the mail body.
I can only suggest to you to read the monolog code for information where a further documentation is missing.
Related
I am using Laravel Log Facade in my app. And I have several services like Mandrill, Twilio, Stripe, etc., that need to be logged in separate file. But when I use Log::useFiles() to set separate file for one of the service wrapper class, like this:
Class Mailer
{
static function init()
{
Log::useFiles(storage_path('logs/mandrill-'.date("Y-m-d").'.log'));
}
static function send()
{
// some code here...
Log::error("Email not sent");
}
}
And I am ending up with log being written in both Laravel log file, and this Mandrill log file.
Is there a way to tell Log to write logs only in one file?
It's generally strange that it does that, because when I use directly Monolog, it writes only in one file, as it should. As far as I know Log Facade is using Monolog.
First of all, keep in mind that if you change the log handlers in your Mailer class you'll change them for the whole application.
Secondly, the reason that after your changes you get logs written to 2 files is that useFiles() does not overwrite the default log handler but adds a new handler to the handlers that Monolog will use. Therefore, you just add a second handler to the list and both of them handle the log message by saving them into different files.
Thirdly, Laravel's Log facade does not provide a way to replace the default handler - if you want to use it you need to use Monolog directly. You can access it by calling Log::getMonolog().
I had change pretend as true in mail config. please check http://laravel.com/docs/4.2/mail#mail-and-local-development
Now log is showing to address like this.
[2014-11-22 17:12:49] production.INFO: Pretending to mail message to: dinukathilanga#gmail.com, bbelekkaya#gmail.com [] []
But i need debug cc emails also. How can i do it?
This is my code.
Mail::send($view, $data, function($message) use ($to, $cc, $subject)
{
foreach ($to as $toUser) {
$message->to($toUser['email'], $toUser['first_name'] . ' ' . $toUser['last_name']);
}
foreach ($cc as $ccUser) {
$message->cc($ccUser['email'], $ccUser['first_name'] . ' ' . $ccUser['last_name']);
}
$message->subject($subject);
});
Allow me to be frank here. I am new to Laravel, but I will try my best to explain this.
I do know how to debug email platforms though, the easiest process is by doing it through C.
I will try to be succint as possible.
Firstly, try using the laravel-debugbar (the latest version is 4).
This is an application that is capable of filtering the PHP Debug Bar.
By using this application you will be able to attach and edit output functions (here is the link for more information: Debug bar.
If this won't work, try debugging through C.
Fristly, you will compile the C program by inserting the debug option, option -g.
Afterwards, you'll launch the gdb into the platform.
Thirdly, you'll break the point in the C program, specifically, insert the break line_number function.
After that, you'll print the variable values in the gdp debugger.
For instance, you'll type commands such as print j and (gdp) p i (I will post the website where I've got this information from; it will give you a more broader walkthrough).
There are various operation for this process.
I strongly advise you visiting:Debug C program using gdb. Hope this helped.
Create a new class named ExtendedMailer for the sake of this example and save the file somewhere the autoloader is able to find it. Depending on where you put the file, you may need to run composer dump-autoload once you've saved it.
<?php
use Illuminate\Mail\Mailer;
class ExtendedMailer extends Mailer
{
protected function logMessage($message)
{
parent::logMessage($message);
$emails = implode(', ', array_keys((array) $message->getCc()));
$this->logger->info("Pretending to mail message to: {$emails}");
}
}
Create a new service provider, somewhere your application is able to load classes. As above, you may need to run composer dump-autoload
The below code simply extends the original MailServiceProvider but allows us to bind a different class to in the IoC, you'll notice the new ExtendedMailer; the class we created earlier. Obviously if you namespaced the class, reflect that change here.
<?php
use Illuminate\Mail\MailServiceProvider;
class ExtendedMailServiceProvider extends MailServiceProvider
{
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
$me = $this;
$this->app->bindShared('mailer', function($app) use ($me)
{
$me->registerSwiftMailer();
// Once we have create the mailer instance, we will set a container instance
// on the mailer. This allows us to resolve mailer classes via containers
// for maximum testability on said classes instead of passing Closures.
$mailer = new ExtendedMailer(
$app['view'], $app['swift.mailer'], $app['events']
);
$this->setMailerDependencies($mailer, $app);
// If a "from" address is set, we will set it on the mailer so that all mail
// messages sent by the applications will utilize the same "from" address
// on each one, which makes the developer's life a lot more convenient.
$from = $app['config']['mail.from'];
if (is_array($from) && isset($from['address']))
{
$mailer->alwaysFrom($from['address'], $from['name']);
}
// Here we will determine if the mailer should be in "pretend" mode for this
// environment, which will simply write out e-mail to the logs instead of
// sending it over the web, which is useful for local dev environments.
$pretend = $app['config']->get('mail.pretend', false);
$mailer->pretend($pretend);
return $mailer;
});
}
}
In your config/app.php, you'll find a line which looks like
'Illuminate\Mail\MailServiceProvider',
You'll need to comment it out and add a line as below
'ExtendedMailServiceProvider',
What this does is replace the mailer which Laravel knows about with the one you've just created. The one you've just created is the same as the default one as it merely extends it, and adds functionality to the logMessage function.
I just switched to monolog and wanted to log my message to the PHP console instead of a file. This might seem obvious for some people, but it took me a little while to figure out how to do that and I couldn't find a similar question/answer on SO.
The example on Monolog's Github readme only shows how to use a file:
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); // <<< uses a file
// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');
But it doesn't state anywhere how messages can be logged to the console. After searching on Google, I landed either on a help page for Symfony or questions of people looking for a way to log to the browser console.
The solution is rather simple. Since the example shows a StreamHandler it's possible to pass in a stream (instead of the path to a file). By default, everything that is echo'ed in PHP is written to php://stdout / php://output so we can simple use one of those as stream for the StreamHandler:
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('php://stdout', Logger::WARNING)); // <<< uses a stream
// add records to the log
$log->warning('Foo');
$log->error('Bar');
Hope this saves somebody some time :)
Some extra details if you want to tweak the default message formatting at the same time:
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
$output = "[%datetime%] %channel%.%level_name%: %message%\n";
$formatter = new LineFormatter($output);
$streamHandler = new StreamHandler('php://stdout', Logger::DEBUG);
$streamHandler->setFormatter($formatter);
$logger = new Logger('LoggerName');
$logger->pushHandler($streamHandler);
I am having some troubles using the logger service in Symfony2. I find it quite confusing.
I am trying to use a Rotating File Handler. To this handler zou can pass 3 paramenters: the filename of the log, maxFiles that the log can divide itself and log level.
I want to pass this parameters from the controller, since I load that data in runtime from a .ini configuration file, but I am not sure how to do it.
How could I do this?
Try the following in your controller:
add a use statement: use Monolog\Handler\RotatingFileHandler;
use it like this: $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
I use error_log for my logging, but I'm realizing that there must be a more idiomatic way to log application progress. is there an info_log ? or equivalent ?
You can use error_log to append to a specified file.
error_log($myMessage, 3, 'my/file/path/log.txt');
Note that you need to have the 3 (message type) in order to append to the given file.
You can create a function early on in your script to wrap this functionality:
function log_message($message) {
error_log($message, 3, 'my/file/path/log.txt');
}
The equivalent is syslog() with the LOG_INFO constant:
syslog(LOG_INFO, 'Message');
If you want to use a file (not a good idea because there is no log rotation and it can fail because of concurrency), you can do:
file_put_contents($filename, 'INFO Message', FILE_APPEND);
I would recommend you to use Monolog:
https://github.com/Seldaek/monolog
You can add the dependency by composer:
composer require monolog/monolog
Then you can initialize a file streaming log, for an app called your-app-name, into the file path/to/your.log, as follow:
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// create a log channel
$log = new Logger('your-app-name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));
Monolog is very powerful, you can implement many types of handlers, formatters, and processors. It worth having a look:
https://github.com/Seldaek/monolog/blob/master/doc/02-handlers-formatters-processors.md
And finally call it like:
// add records to the log
$log->warning('Foo');
$log->error('Bar');
In order to make it global, I recommend you to add it to your dependency injector, if you have one, or use a singleton with static calls.
Let me know if you want more details about this.