loggly_使用Loggly更有效地记录PHP

loggly

This article was sponsored by Loggly. Thank you for supporting the sponsors who make SitePoint possible.

本文由Loggly赞助。 感谢您支持使SitePoint成为可能的赞助商。

Server overloaded, library throwing an exception, error while sending email: these errors are unfortunately part of every system. If you’re in charge of making a system function well, that’s still cold comfort. What’s more, I bet you already have all the data you need to solve them sitting in your log files.

服务器超载,库抛出异常,发送电子邮件时出错:不幸的是,这些错误是每个系统的一部分。 如果您负责使系统正常运行,那仍然很舒适。 而且,我敢打赌,您已经将解决​​它们所需的所有数据放在日志文件中。

But having access to that data doesn’t really help unless you have a way to store, process, and analyse that data. In this article I’ll explain how to use this data more effectively by using a PHP logging library with a proper log management solution (in this case, Loggly). I’ll also show an example of how to use a log management service to store and analyze them easier.

但是,除非您有一种存储,处理和分析数据的方法,否则访问这些数据并没有真正的帮助。 在本文中,我将说明如何通过将PHP日志记录库与适当的日志管理解决方案(在本例中为Loggly)结合使用来更有效地使用此数据。 我还将展示一个示例,说明如何使用日志管理服务更轻松地存储和分析它们。

PHP日志 (PHP Logging)

When logging with PHP, we tend to use the error_log and trigger_error functions, or we can use an error handler to make the logging process more generic. If you choose to do it this way, you’ll need to wrap your functions inside some kind of object to make things cleaner and flexible. You can also forward your logs directly to your system to handle them, using the syslog function.

使用PHP进行日志记录时,我们倾向于使用error_logtrigger_error函数,或者可以使用错误处理程序使日志记录过程更加通用。 如果选择以这种方式进行操作,则需要将函数包装在某种对象中,以使事情更整洁,更灵活。 您还可以使用syslog函数将日志直接转发到系统以进行处理。

openlog('php', LOG\_CONS | LOG\_NDELAY | LOG\_PID, LOG\_USER | LOG\_PERROR); syslog(LOG\_ERR, 'Error!'); syslog(LOG\_INFO, 'Hello World!'); closelog();

But what would you do if you had to log to multiple places at the same time, or you were sending logs to a given service depending on the error level? Rather than using built-in tools, it’s often easier to use logging libraries.

但是,如果必须同时登录到多个位置,或者根据错误级别将日志发送到给定的服务,该怎么办? 与其使用内置工具,不如使用日志记录库。

为什么我使用独白 (Why I Use Monolog)

While some recommend libraries like log4php, KLogger and Monolog try to solve those common problems, they have a few limitations, and Monolog has a lot of advantages over them.

虽然一些建议像图书馆log4phpKLogger独白尝试解决这些共同的问题,他们有一些限制,以及独白有很多对他们的优势。

  • It’s PSR-3 compliant

    符合PSR-3

  • Includes handlers for a variety of services, including Loggly.

    包括针对各种服务的处理程序,包括Loggly。
  • Support for formatters to customise your logs output.

    支持格式化程序以自定义日志输出。

  • Helpers for development logging like the BrowserConsoleHandler for logging to the browser console.

    用于开发日志记录的助手,例如用于登录到浏览器控制台的BrowserConsoleHandler。

Make sure to check the documentation for more details about the package. Most popular frameworks include Monolog out of the box, so check the full list on the documentation. If you don’t have Monolog installed, you can add it to a project using Composer.

确保检查文档以获取有关该软件包的更多详细信息。 最受欢迎的框架都包括开箱即用的Monolog,因此请查看文档中的完整列表。 如果未安装Monolog,则可以使用Composer将其添加到项目中。

composer require monolog/monolog

大规模采伐问题 (The Problems of Logging at Scale)

Since logging requires writing to the disk, doing backups and searching files, some companies create a separate service to handle the job (usually a set of scripts or apps to grep files searching for info when some kind of error occurs). As your company or service scales up, this can quickly become a nightmare for your developers and analysts. Another, better, alternative is a cloud based service for their log storage and analysis and this has a lot of benefits, as we’ll discuss further in this article.

由于日志记录需要写入磁盘,进行备份和搜索文件,因此一些公司创建了一项单独的服务来处理这项工作(通常是一组脚本或应用程序,用于在发生某种错误时grep文件来搜索信息)。 随着公司或服务规模的扩大,这可能很快成为开发人员和分析师的噩梦。 另一个更好的替代方法是基于云的服务进行日志存储和分析,这样做有很多好处,我们将在本文中进一步讨论。

什么是Loggly? (What Is Loggly?)

There are several log management services that will make storing and analyzing your logs easier. Loggly is the most popular one and it has several ways to integrate with PHP. Once Loggly receives your logs, you’ll be able to search, group and visualize your data in a really impressive way. You can try it for free. You only pay if you have sizable traffic on your site. Let’s start first by looking on how to install it on your server to track your system logs.

有几种日志管理服务可简化日志的存储和分析。 Loggly是最受欢迎的一种,它有几种与PHP集成的方式。 Loggly收到日志后,您将能够以一种非常令人印象深刻的方式搜索,分组和可视化数据。 您可以免费试用。 仅当您的网站上有大量流量时,您才需要付费。 首先,让我们开始研究如何将其安装在服务器上以跟踪系统日志。

将Loggly与Monolog结合使用 (Using Loggly with Monolog)

If you decided to go with the Monolog package library for your logging process, it’s very easy to get it integrated with any log management service, including Loggly.

如果您决定将Monolog软件包库用于日志记录过程,则很容易将其与任何日志管理服务(包括Loggly)集成在一起。

By default, it comes with a LogglyHandler for Loggly.

默认情况下,它带有LogglyHandler的LogglyHandler。

$logger = new \Monolog\Logger('local_test_app'); $logger->pushHandler(new \Monolog\Handler\LogglyHandler('YOUR_TOKEN/tag/monolog'));

After creating a Monolog instance, we’ll push our handler to the list of registered handlers, and you’ll need to provide your token as previously mentioned. The tag part is optional, but it’s always a good idea to separate your log entries by tagging them accordingly. Now we’re ready to start logging to our service using Monolog.

创建Monolog实例后,我们将处理程序推送到已注册处理程序列表中,并且您需要如前所述提供令牌。 标签部分是可选的,但是始终通过相应地标记它们来分隔日志条目始终是一个好主意。 现在,我们准备开始使用Monolog登录到我们的服务。

$logger->addInfo("Info test from monolog"); //$logger->addWarning("Warning test from monolog");
Loggly and Monolog

与Laravel Loggly (Loggly with Laravel)

Since Laravel is using Monolog for the logging process, we can easily bind our handler to it.

由于Laravel在记录过程中使用了Monolog,因此我们可以轻松地将其处理程序绑定到它。

$handler = new \Monolog\Handler\LogglyHandler('YOUR_TOKEN/tag/monolog'); $logger = Log::getMonolog(); $logger->pushHandler($handler); // using the Log facade Log::info("Test from Laravel"); Log::warning("Test from Laravel");

在Heroku上配置Loggly (Configuring Loggly on Heroku)

When you move your application to production, you want to make sure that your logs tracking is working properly. In this section we are going to attach Loggly to our Heroku application. Heroku uses Log Drains to help you forward your logs to an external logging service. You can check the documentation for more details about the installation process.

当您将应用程序移至生产环境时,您要确保日志跟踪正常运行。 在本节中,我们将把Loggly附加到我们的Heroku应用程序中。 Heroku使用Log Drains帮助您将日志转发到外部日志服务。 您可以查看文档以获取有关安装过程的更多详细信息。

heroku drains:add https://logs-01.loggly.com/bulk/TOKEN/tag/heroku --app HEROKU_APP_NAME

You need to update the TOKEN with your actual token that you can find on the Source setup > Customer Tokens page. The HEROKU_APP_NAME can be omitted if you’re already logged into your Heroku instance, otherwise you need to specify your Heroku application name.

您需要更新的TOKEN与实际令牌,你可以找到源设置>客户令牌页面上。 如果您已经登录Heroku实例,则可以省略HEROKU_APP_NAME ,否则,您需要指定Heroku应用程序名称。

The drain URL ends with tag/heroku, this will help us filter our logs using the defined tag, we will talk more about this later.

引流网址以tag/heroku结尾,这将帮助我们使用定义的标签过滤日志,稍后我们将详细讨论。

Loggly and Heroku

Loggly can be easily integrated with any external service like Heroku. Check the Loggly documentation for an overview of log transmission methods and available scripts or libraries.

Loggly可以轻松地与任何外部服务(如Heroku)集成。 查看Loggly文档以获取日志传输方法以及可用脚本或概述

使用Loggly分析日志 (Analyzing Logs with Loggly)

Now that we’ve discussed how to send your logs to Loggly, we can start analysing and working with our data. The search page provides a set of tools to filter, analyze and visualise our logs.

现在,我们已经讨论了如何将您的日志发送到Loggly,我们可以开始分析和处理数据了。 搜索页面提供了一组工具,用于过滤,分析和可视化我们的日志。

Loggly's search page

The dashboard shows a timeline of your events along with a list of logs at the bottom. The top of the page contain a search box and a date range to filter events, you can select the last 30 minutes or specify a custom date range for example and click search to validate.

仪表板在底部显示事件的时间线以及日志列表。 页面顶部包含一个搜索框和一个日期范围以过滤事件,例如,您可以选择最近30分钟或指定一个自定义日期范围,然后单击“搜索”进行验证。

过滤日志 (Filtering Logs)

You can use the search input to filter data using a specific term like “email” or “event_*”. Loggly will search inside the body of your log entries and display the result at the bottom of the page. You can also use fields for searching, like “tag:monolog” to filter the events sent previously from Monolog. The left side menu is called the Dynamic Field Explorer and it can help you identify the available field filters.

您可以使用搜索输入来使用诸如“电子邮件”或“ event_ *”之类的特定术语过滤数据。 Loggly将在日志条目的正文中进行搜索,并将结果显示在页面底部。 您还可以使用字段进行搜索,例如“ tag:monolog”以过滤先前从Monolog发送的事件。 左侧菜单称为“动态字段资源管理器”,它可以帮助您识别可用的字段过滤器。

Loggly's field explorer

Let’s take the following examples to better understand how to analyze logs.

让我们以下面的示例更好地了解如何分析日志。

内部服务器错误 (Internal Server Errors)

An internal server error is thrown when your server was unable to process a valid request from the user. In PHP, details about this error can be found inside your Apache logs, if you register an error handler using PHP you can group your own log files so you can analyze them and fix errors according to the log message.

当服务器无法处理来自用户的有效请求时,将引发内部服务器错误。 在PHP中,有关该错误的详细信息可以在Apache日志中找到,如果使用PHP注册错误处理程序,则可以对自己的日志文件进行分组,以便您可以分析它们并根据日志消息修复错误。

You can use the Field Explorer widget on the left side of the page to filter down logs using the apache 5XX status code. The search can be specific like “apache.status:500” or you can make it more generic like “apache.status:[500 TO 599]”.

您可以使用页面左侧的Field Explorer小部件使用apache 5XX状态代码过滤日志。 搜索可以是特定的,例如“ apache.status:500”,也可以是更通用的,例如“ apache.status:[500 TO 599]”。

Internal server error alerts

致命错误 (Fatal Errors)

In PHP, when a fatal error is thrown, the program will stop the execution and log the error to your system. Because fatal errors are not supposed to happen on production, Loggly provides an easy way to track errors’ severity from different sources. The “syslog.appName:php” term will only show PHP logs, now we need to show errors from a specific severity using the syslog.severity:Error term, we can also specify a range like “syslog.severity:[Warning TO Error]”. You can read more about the list of available fields on the documentation.

在PHP中,当引发致命错误时,程序将停止执行并将错误记录到您的系统中。 因为致命错误不应在生产中发生,所以Loggly提供了一种简便的方法来跟踪来自不同来源的错误的严重性。 “ syslog.appName:php”一词仅显示PHP日志,现在我们需要使用syslog.severity:Error词显示特定严重性的错误,我们还可以指定一个范围,例如“ syslog.severity:[警告错误” ]”。 您可以阅读有关文档中可用字段列表的更多信息

syslog.appName:php AND syslog.severity:Error

Most of the time we’re displaying results as a list, but you may want to use another graph from the list of charts at the bottom of the page.

大多数情况下,我们将结果显示为列表,但您可能希望使用页面底部图表列表中的另一个图表。

Pie chart showing alert severity

快讯 (Alerts)

One of my favorite features on Loggly is the alerts tool. You can configure Loggly to send notifications to your email or another service whenever an action occurs on your application. Lets go through the process in detail.

我在Loggly上最喜欢的功能之一是警报工具。 您可以将Loggly配置为在应用程序上发生操作时将通知发送到您的电子邮件或其他服务。 让我们详细介绍一下该过程。

First you need to create a new search and save it. Lets take this search for example: “syslog.appName:php AND php.level:”Fatal Error””

首先,您需要创建一个新搜索并将其保存。 让我们以该搜索为例:“ syslog.appName:php和php.level:“致命错误””

This will show us the list of PHP fatal errors on our system. Next, we need to save this search criteria. Click on the little star on the top right of the dashboard page, select the “Save this search as…” item and name the search.

这将向我们显示系统上PHP致命错误的列表。 接下来,我们需要保存此搜索条件。 单击仪表板页面右上角的小星星,选择“将此搜索另存为...”项并命名搜索。

Fatal errors
Adding a notification for fatal errors

Now we can go to the list of alerts and click Add new to create a new one. After giving a name and a description to your alert, you can select a saved search from the list and a condition (Alert if count is >= 1 within 5 minutes). For my example I will send an email notification, but if you have a service that automatically passes the error to your team for verification, you can configure it to post it to your endpoint. You can read more about alerts on the documentation.

现在,我们可以转到警报列表,然后单击“添加新的”以创建一个新的警报。 为警报指定名称和描述后,您可以从列表和条件中选择一个保存的搜索(如果计数在5分钟内大于等于1,则发出警报)。 在我的示例中,我将发送电子邮件通知,但是如果您有一项服务会自动将错误传递给您的团队进行验证,则可以对其进行配置以将其发布到您的端点。 您可以在文档中阅读有关警报的更多信息。

A notification for a fatal error

结论 (Conclusion)

Loggly can change the way you deal with your logs, from regexp search to archiving. The service also has great UX, and the documentation is very straightforward, covering the majority of the possibilities. You can start with a free trial to test all the features. If you have any questions, feel free to post them below and I will do my best to answer them.

Loggly可以改变您处理日志的方式,从正则表达式搜索到归档。 该服务还具有出色的UX,并且文档非常简单,涵盖了大多数可能性。 您可以从免费试用开始,以测试所有功能。 如果您有任何疑问,请随时在下面发布,我会尽力回答。

How do you make PHP logging easier?

如何使PHP日志记录更容易?

翻译自: https://www.sitepoint.com/effective-php-logging-loggly/

loggly

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值