SlideShare a Scribd company logo
Logs no Laravel 5.6
7Masters - Laravel
> whoami
• Software Developer
• DevOps Engineer
• PHP (Zend Certified PHP Engineer)
• Linux (Linux Foundation Certified
SysAdmin)
• MCSE Cloud Platform and
Infrastructure (Azure)
• MSCE Data Management and
Analytics (SQL Server)
Logs no Laravel 5.6 @ 7masters Laravel
Logs no Laravel 5.6 @ 7masters Laravel
Mas.. O que são Logs?
Até o Laravel 5.5 ...
<?php
return [
/*
|--------------------------------------------
| Logging Configuration
|--------------------------------------------
| Available Settings: "single", "daily",
| "syslog", "errorlog"
*/
'log' => env('APP_LOG', 'single'),
'log_level' => env('APP_LOG_LEVEL', 'debug'),
<?php
// bootstrap.php
$app->configureMonologUsing(function ($monolog) {
$monolog->pushHandler(...);
});
return $app;
Laravel 5.6+
<?php
return [
// Default Log Channel
'default' => env('LOG_CHANNEL', 'stack'),
/* Log Channels
|------------------------------------------------
| Available Drivers: "single", "daily", "slack",
| "syslog", "errorlog", "monolog", "custom",
| "stack“
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single', 'slack'],
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => 'critical',
],
],
];
E quando sua aplicação crescer...
Monolog
Monolog Handlers
<?php
return [
'channels' => [
'stdout' => [
'driver' => 'monolog',
'handler' => MonologHandlerStreamHandler::class,
'with' => [
'stream' => 'php://stdout’,
],
],
'insightops' => [
'driver' => 'monolog',
'handler' => GmsantosMonologHandlerInsightOpsHandler::class,
'with' => [
'token' => env('INSIGHTOPS_TOKEN'),
],
],
'custom' => [
'driver' => 'custom',
'via' => AppLoggingCreateCustomLogger::class,
],
],
];
Exemplo: Monitoramento de Queues
7Masters - Laravel
public function boot()
{
Queue::before(function (JobProcessing $event) {
Log::channel('queue')->info('Processing {job} on {connectionName}', [
'status' => 'processing',
'job' => $event->job->payload()['displayName'] ?? get_class($event->job),
'connectionName' => $event->connectionName,
]);
});
Queue::after(function (JobProcessed $event) {
Log::channel('queue')->info('Processed {job} on {connectionName}', [
'status' => 'done',
'job' => $event->job->payload()['displayName'] ?? get_class($event->job),
'connectionName' => $event->connectionName,
]);
});
Queue::failing(function (JobFailed $event) {
Log::channel('queue')->error('Failed {job} on {connectionName}', [
'status' => 'failed',
'job' => $event->job->payload()['displayName'] ?? get_class($event->job),
'connectionName' => $event->connectionName,
'exceptionMessage' => $event->exception->getMessage(),
'expection' => $event->exception,
]);
});
}
Logs no Laravel 5.6 @ 7masters Laravel
Logs no Laravel 5.6 @ 7masters Laravel
Referências
• PR original Logging Laravel 5.6 (https://github.com/laravel/framework/pull/21152)
• Talk sobre Logs (https://www.slideshare.net/gmsantos/logs-pra-que-te-quero-79378404)
• Config de logs Laravel 5.5 (https://github.com/laravel/laravel/blob/5.5/config/app.php)
• Customizando logs no Laravel 5.5 (https://laravel.com/docs/5.5/errors#custom-monolog-
configuration)
• Config de logs Laravel 5.6 (https://github.com/laravel/laravel/blob/master/config/logging.php)
• Monolog (https://packagist.org/packages/monolog/monolog)
• Handlers do Monolog (https://seldaek.github.io/monolog/doc/02-handlers-formatters-
processors.html#handlers)
• Channels custumizados (https://laravel.com/docs/5.6/logging#customizing-monolog-for-
channels)
• Events de Queue (https://laravel.com/docs/5.6/queues#job-events)
gmsantos
gmsantos__
gmsantos
gmsantos
Código disponível em:
https://github.com/gmsantos/7masters-laravel-log
Obrigado!
gmsantos
gmsantos__
gmsantos
gmsantos
Código disponível em:
https://github.com/gmsantos/7masters-laravel-log

More Related Content

PDF
Making MySQL Administration a Breeze - A Look Into a MySQL DBA's Toolchest
PPTX
2012 dtcc-itpub-runing-critical-data-on-mysql
PPT
SaltConf14 - Brendan Burns, Google - Management at Google Scale
PPTX
Laravel 5.6 new features and updates
PDF
SaltConf14 - Forrest Alvarez, Choice Hotels - Salt Formulas and States
PDF
Salt conf 2014 - Using SaltStack in high availability environments
ODP
Nagios Conference 2012 - Mike Weber - Failover
PDF
ProxySQL - High Performance and HA Proxy for MySQL
Making MySQL Administration a Breeze - A Look Into a MySQL DBA's Toolchest
2012 dtcc-itpub-runing-critical-data-on-mysql
SaltConf14 - Brendan Burns, Google - Management at Google Scale
Laravel 5.6 new features and updates
SaltConf14 - Forrest Alvarez, Choice Hotels - Salt Formulas and States
Salt conf 2014 - Using SaltStack in high availability environments
Nagios Conference 2012 - Mike Weber - Failover
ProxySQL - High Performance and HA Proxy for MySQL

What's hot (19)

PDF
MHA (MySQL High Availability): Getting started & moving past quirks
PDF
High Concurrency Architecture and Laravel Performance Tuning
ODP
Nagios Conference 2014 - Andy Brist - Nagios XI Failover and HA Solutions
PDF
M|18 Migrating from Oracle and Handling PL/SQL Stored Procedures
PPTX
Blue host openstacksummit_2013
ODP
Nagios Conference 2013 - Eric Stanley and Andy Brist - API and Nagios
PDF
OSDC 2014: Colin Charles - Automated MySQL failover with MHA: getting started...
PDF
Training Slides: Advanced 304: Upgrading From Native MySQL Replication To Tun...
PPTX
Ansible MySQL MHA
PDF
NY Meetup: Scaling MariaDB with Maxscale
PPT
Zarafa SummerCamp 2012 - Zarafa 7.1 features
PDF
Salt conf 2014-installing-openstack-using-saltstack-v02
KEY
Nginx in production
PDF
Mysql8 advance tuning with resource group
PPTX
ChinaNetCloud Online Lecture:Something About Tshark
PPTX
Maria DB Galera Cluster for High Availability
PPTX
Saltstack with Zabbix
PDF
Saltcheck: a tool in the salt toolbox
PPTX
DB Floripa - ProxySQL para MySQL
MHA (MySQL High Availability): Getting started & moving past quirks
High Concurrency Architecture and Laravel Performance Tuning
Nagios Conference 2014 - Andy Brist - Nagios XI Failover and HA Solutions
M|18 Migrating from Oracle and Handling PL/SQL Stored Procedures
Blue host openstacksummit_2013
Nagios Conference 2013 - Eric Stanley and Andy Brist - API and Nagios
OSDC 2014: Colin Charles - Automated MySQL failover with MHA: getting started...
Training Slides: Advanced 304: Upgrading From Native MySQL Replication To Tun...
Ansible MySQL MHA
NY Meetup: Scaling MariaDB with Maxscale
Zarafa SummerCamp 2012 - Zarafa 7.1 features
Salt conf 2014-installing-openstack-using-saltstack-v02
Nginx in production
Mysql8 advance tuning with resource group
ChinaNetCloud Online Lecture:Something About Tshark
Maria DB Galera Cluster for High Availability
Saltstack with Zabbix
Saltcheck: a tool in the salt toolbox
DB Floripa - ProxySQL para MySQL
Ad

Similar to Logs no Laravel 5.6 @ 7masters Laravel (20)

PDF
Basic MySQL Troubleshooting for Oracle DBAs
PDF
The MySQL SYS Schema
PDF
MySQL sys schema deep dive
PDF
Mysql nowwhat
PDF
MySQL sys schema deep dive
PPTX
MySQL Tech Tour 2015 - Manage & Tune
PDF
제3회난공불락 오픈소스 인프라세미나 - MySQL
PDF
MySQL Performance Schema in 20 Minutes
PDF
MySQL Webinar Series 4/4 - Manage & tune
PDF
Basic MySQL Troubleshooting for Oracle Database Administrators
PPTX
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
PPTX
MariaDB Galera Cluster
PDF
[오픈소스컨설팅] 쿠버네티스와 쿠버네티스 on 오픈스택 비교 및 구축 방법
PDF
Curso de MySQL 5.7
PDF
MariaDB 5.5 and what comes next - Percona Live NYC 2012
PDF
Ipc mysql php
PPT
20131003 pizzasessie db-security
PDF
What's new in MySQL 5.7, Oracle Virtual Technology Summit, 2016
PDF
MySQL PHP native driver : Advanced Functions / PHP forum Paris 2013
PDF
MySQL 5.7 innodb_enhance_partii_20160527
Basic MySQL Troubleshooting for Oracle DBAs
The MySQL SYS Schema
MySQL sys schema deep dive
Mysql nowwhat
MySQL sys schema deep dive
MySQL Tech Tour 2015 - Manage & Tune
제3회난공불락 오픈소스 인프라세미나 - MySQL
MySQL Performance Schema in 20 Minutes
MySQL Webinar Series 4/4 - Manage & tune
Basic MySQL Troubleshooting for Oracle Database Administrators
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
MariaDB Galera Cluster
[오픈소스컨설팅] 쿠버네티스와 쿠버네티스 on 오픈스택 비교 및 구축 방법
Curso de MySQL 5.7
MariaDB 5.5 and what comes next - Percona Live NYC 2012
Ipc mysql php
20131003 pizzasessie db-security
What's new in MySQL 5.7, Oracle Virtual Technology Summit, 2016
MySQL PHP native driver : Advanced Functions / PHP forum Paris 2013
MySQL 5.7 innodb_enhance_partii_20160527
Ad

More from Gabriel Machado (14)

PPTX
Implementando PSR-3 com Monolog
PPTX
GitHub Actions @ Oktober Cloud 2019
PPTX
Logs, pra que te quero! @ Meetup PHP Vale
PDF
Implementando PSR-3 com Monolog @ PHP Community Summit 2019
PPTX
Symfony Flex & Dependency Injection @ Symfony Live São Paulo 2019
PPTX
Pipelines de CI/CD com Azure @ Oktober Cloud
PPTX
Symfony Flex @ PHP Community Summit 2018
PPTX
Symfony Flex @ 2º Meetup PHPVale
PPTX
O que não fazer ao atualizar para o PHP 7 @ TDC SP 2018
PPTX
Continuous Delivery com Docker, OpenShift e Jenkins @ TDC FLP 2018
PPTX
Relatórios gerenciais com MySQL @ 7Masters MySQL
PPTX
Logs, pra que te quero! @ PHP Community Summit by locaweb 2017
PPTX
Logs, pra que te quero! @ TDC SP 2017
PPTX
Novidades do Laravel 5.3 @ 11º Meetup Laravel SP
Implementando PSR-3 com Monolog
GitHub Actions @ Oktober Cloud 2019
Logs, pra que te quero! @ Meetup PHP Vale
Implementando PSR-3 com Monolog @ PHP Community Summit 2019
Symfony Flex & Dependency Injection @ Symfony Live São Paulo 2019
Pipelines de CI/CD com Azure @ Oktober Cloud
Symfony Flex @ PHP Community Summit 2018
Symfony Flex @ 2º Meetup PHPVale
O que não fazer ao atualizar para o PHP 7 @ TDC SP 2018
Continuous Delivery com Docker, OpenShift e Jenkins @ TDC FLP 2018
Relatórios gerenciais com MySQL @ 7Masters MySQL
Logs, pra que te quero! @ PHP Community Summit by locaweb 2017
Logs, pra que te quero! @ TDC SP 2017
Novidades do Laravel 5.3 @ 11º Meetup Laravel SP

Recently uploaded (20)

PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Transform Your Business with a Software ERP System
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
AI in Product Development-omnex systems
PPTX
Introduction to Artificial Intelligence
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Essential Infomation Tech presentation.pptx
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
top salesforce developer skills in 2025.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
Navsoft: AI-Powered Business Solutions & Custom Software Development
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Softaken Excel to vCard Converter Software.pdf
Upgrade and Innovation Strategies for SAP ERP Customers
Transform Your Business with a Software ERP System
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Which alternative to Crystal Reports is best for small or large businesses.pdf
How Creative Agencies Leverage Project Management Software.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
AI in Product Development-omnex systems
Introduction to Artificial Intelligence
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Essential Infomation Tech presentation.pptx
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
top salesforce developer skills in 2025.pdf
How to Migrate SBCGlobal Email to Yahoo Easily

Logs no Laravel 5.6 @ 7masters Laravel

  • 1. Logs no Laravel 5.6 7Masters - Laravel
  • 2. > whoami • Software Developer • DevOps Engineer • PHP (Zend Certified PHP Engineer) • Linux (Linux Foundation Certified SysAdmin) • MCSE Cloud Platform and Infrastructure (Azure) • MSCE Data Management and Analytics (SQL Server)
  • 5. Mas.. O que são Logs?
  • 6. Até o Laravel 5.5 ... <?php return [ /* |-------------------------------------------- | Logging Configuration |-------------------------------------------- | Available Settings: "single", "daily", | "syslog", "errorlog" */ 'log' => env('APP_LOG', 'single'), 'log_level' => env('APP_LOG_LEVEL', 'debug'), <?php // bootstrap.php $app->configureMonologUsing(function ($monolog) { $monolog->pushHandler(...); }); return $app;
  • 7. Laravel 5.6+ <?php return [ // Default Log Channel 'default' => env('LOG_CHANNEL', 'stack'), /* Log Channels |------------------------------------------------ | Available Drivers: "single", "daily", "slack", | "syslog", "errorlog", "monolog", "custom", | "stack“ */ 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['single', 'slack'], ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', ], 'slack' => [ 'driver' => 'slack', 'url' => env('LOG_SLACK_WEBHOOK_URL'), 'username' => 'Laravel Log', 'emoji' => ':boom:', 'level' => 'critical', ], ], ];
  • 8. E quando sua aplicação crescer...
  • 11. <?php return [ 'channels' => [ 'stdout' => [ 'driver' => 'monolog', 'handler' => MonologHandlerStreamHandler::class, 'with' => [ 'stream' => 'php://stdout’, ], ], 'insightops' => [ 'driver' => 'monolog', 'handler' => GmsantosMonologHandlerInsightOpsHandler::class, 'with' => [ 'token' => env('INSIGHTOPS_TOKEN'), ], ], 'custom' => [ 'driver' => 'custom', 'via' => AppLoggingCreateCustomLogger::class, ], ], ];
  • 12. Exemplo: Monitoramento de Queues 7Masters - Laravel
  • 13. public function boot() { Queue::before(function (JobProcessing $event) { Log::channel('queue')->info('Processing {job} on {connectionName}', [ 'status' => 'processing', 'job' => $event->job->payload()['displayName'] ?? get_class($event->job), 'connectionName' => $event->connectionName, ]); }); Queue::after(function (JobProcessed $event) { Log::channel('queue')->info('Processed {job} on {connectionName}', [ 'status' => 'done', 'job' => $event->job->payload()['displayName'] ?? get_class($event->job), 'connectionName' => $event->connectionName, ]); }); Queue::failing(function (JobFailed $event) { Log::channel('queue')->error('Failed {job} on {connectionName}', [ 'status' => 'failed', 'job' => $event->job->payload()['displayName'] ?? get_class($event->job), 'connectionName' => $event->connectionName, 'exceptionMessage' => $event->exception->getMessage(), 'expection' => $event->exception, ]); }); }
  • 16. Referências • PR original Logging Laravel 5.6 (https://github.com/laravel/framework/pull/21152) • Talk sobre Logs (https://www.slideshare.net/gmsantos/logs-pra-que-te-quero-79378404) • Config de logs Laravel 5.5 (https://github.com/laravel/laravel/blob/5.5/config/app.php) • Customizando logs no Laravel 5.5 (https://laravel.com/docs/5.5/errors#custom-monolog- configuration) • Config de logs Laravel 5.6 (https://github.com/laravel/laravel/blob/master/config/logging.php) • Monolog (https://packagist.org/packages/monolog/monolog) • Handlers do Monolog (https://seldaek.github.io/monolog/doc/02-handlers-formatters- processors.html#handlers) • Channels custumizados (https://laravel.com/docs/5.6/logging#customizing-monolog-for- channels) • Events de Queue (https://laravel.com/docs/5.6/queues#job-events)

Editor's Notes

  • #2: Boa noite, hoje vou falar sobre logs no Laravel 5.6.. Como ele funciona por baixo dos panos, como você pode configura-lo e o que vc pode fazer com tudo isso.
  • #3: Me apresentando, Eu sou o Gabriel, trabalho atualmente na Leroy Merlin como desenvolvedor e atuo também com devops. Tenho algumas certificações na área, de PHP, Linux, Microsoft...  Quem me conhece sabe que gosto de certificações como forma de estudo, se alguem quiser podemos trocar uma ideia depois...
  • #4: E quem me conhece sabe também que sigo "alguns" repositórios no github, incluse o repositório do Laravel... Por exemplo essa é minha tela de notificações do github.. Isso é o que vejo depois de um fim de semana comum... só do Laravel tem mais de 300 notificações... e em uma dessas notificações teve um pr que me chamou a atenção
  • #5: Que foi esse PR... uma proposta de refazer o componente de Log no Laravel 5.6... Esse PR em específico foi retrabalhado pelo Taylor... aqui consta como fechado mas entrou.. E como me interesso por essa parte de Logs, acabei acompanhando esse PR até ser mergeado
  • #6: Pra deixar todos na mesma página, acredito que a maioria já teve contato alguma vez com um arquivo de logs, tenho um talk falando sobre isso.. Mas como funciona os logs no Laravel?
  • #7: Até a versão 5.5, essa configuração era feita dentro do config/app ... tinha algumas opções de logs, single file, arquivos diarios... era definido o nível de log E qualquer coisa que fugia disso era preciso alterar o arquivo de bootstrap com o configureMonologUsing()
  • #8: Com o Laravel 5.6, temos uma maior liberdade para definir nossos logs, foi introduzido o conceito de channels de logs e podemos combinar mais de um channel Nesse exemplo aqui, temos dois channels, um que salva num arquivo... é possivel configurar o caminho e o nivel de log individualmente e temos tbm logs criticos que recebemos uma notificação no slack em casos criticos... Isso é combinado com um driver de stack e assim os logs são salvos e enviados ao mesmo tempo para o slack
  • #9: Até aqui temos umas estratégia boa para logs... mas e quando sua aplicação crescer ? Você não vai ver arquivo por arquivo e cada servidor e pode ser preciso usar um serviço que não vem por padrão no Laravel...
  • #10: Pensando nisso, o Laravel já utiliza desde a versão 4 o Monolog.. Ele é uma biblioteca especializada em Log que inclui muitos outros destinos para logs
  • #11: Eles são chamados de Handlers esses destinos, e temos uma lista de alguns disponíveis ... podem ver que temos mais de 10 aqui...
  • #12: E como utilizar isso no Laravel? Qualquer um daqueles handlers podemos declarar a classe de handler usando o driver monolog, inserindo os parametrôs do construtor dentro do with É possível tbm usar custon Handlers de terceiros que não existam no monolog, como temos no segundo caso.. Ou em casos mais extremos temos o driver custom que utilizamos de forma parecida com o configureUsingMonolog do Laravel 5.5... para uma migração, esse ultimo seria o mais fácil.
  • #13: E o que podemos fazer com toda essa configuração? Um exemplo bem simples é implementar o monitoramento de Queues do Laravel
  • #14: Podemos criar um provider que escuta alguns eventos da Queue e enviamos esse evento para um log... Aqui estou escutando os eventos de inicio do Job, job processado com sucesos ou erro na execução, juntamente com o erro que ocorreu E ao enviar isso para um serviço externo
  • #15: Podemos criar um dashboard bom informações sobre nosso sistema, como quantidade de Jobs durante o tempo, jobs que falharam
  • #16: Os tipos de Jobs em execução.. E assim vai..
  • #17: Segue aqui algumas referencias que usei para essa talk
  • #18: E é isso, segue aqui meus contatos, alguns dos códigos estão disponíveis nesse github 
  • #19: e valeu!