jenkins 构建节点_您构建了节点应用程序,但正在登录

本文介绍了日志记录在开发应用程序中的重要性,特别是在生产环境中定位问题的关键作用。建议开发人员避免使用`console.log`,而应采用专业的日志库,如Winston或Bunyan,以支持不同级别的日志记录和过滤。文章强调了日志应包含源、时间戳和上下文信息,并提倡正确使用日志级别。在生产环境中,应根据需要调整日志级别以平衡性能和诊断需求。最后,建议将当前日志级别存储为环境变量,以便灵活切换。
摘要由CSDN通过智能技术生成

jenkins 构建节点

Logging is a crucial part of developing an application. When the app is in production, logs are necessary to identify the problem if something goes wrong. So if you are a developer, you should ask yourself this question: “Am I logging the right way?”

日志记录是开发应用程序的关键部分。 当应用程序投入生产时,如果出现问题,则需要日志来识别问题。 因此,如果您是开发人员,则应该问自己一个问题:“我是否以正确的方式登录?”

In this article, we are going to provide an answer to that question. We will discuss the best practices developers — especially Node.js developers — should follow when logging their application events.

在本文中,我们将为该问题提供答案。 我们将讨论开发人员(尤其是Node.js开发人员)在记录其应用程序事件时应遵循的最佳实践。

为什么日志很重要? (Why Are Logs Important?)

No matter how careful we are when developing an application, it’s a difficult task to make it 100% secure and bug-free. We try to find and solve most of the problems during development by testing and debugging. Still, we won’t be able to catch all of them.

无论我们在开发应用程序时有多谨慎,要使其100%安全且无错误,这都是一项艰巨的任务。 我们尝试通过测试和调试来发现并解决开发过程中的大多数问题。 不过,我们将无法捕获所有这些。

Because of these remaining errors, applications running in production might behave in unexpected ways in certain situations. Sometimes, they can be really critical. They may even crash the application entirely. In such a case, can we run a debugger to figure out what went wrong with our application? No, it’s not the most practical idea.

由于仍然存在这些错误,因此在某些情况下,生产环境中运行的应用程序可能会以意外方式运行。 有时,它们可能非常关键。 他们甚至可能完全使应用程序崩溃。 在这种情况下,我们可以运行调试器来找出应用程序出了什么问题吗? 不,这不是最实际的想法。

Instead, we use application logs to understand how and why the application is behaving differently. For this, we have to set up our application to record information about its events and errors. And this is what we call logging. Logging helps us identify problems with an application running in production.

相反,我们使用应用程序日志来了解应用程序的行为方式以及原因。 为此,我们必须设置应用程序以记录有关其事件和错误的信息。 这就是我们所说的日志记录。 日志记录可帮助我们确定生产环境中运行的应用程序存在的问题。

记录最佳做法 (Logging Best Practices)

Since logs are quite important, we need to follow logging practices that will help us easily identify problems and their causes.

由于日志非常重要,因此我们需要遵循日志记录做法,这将有助于我们轻松地确定问题及其原因。

1.不要使用console.log (1. Don’t use console.log)

Developers tend to rely on Node’s console.log function to log application events since it’s easily accessible, needs no additional setup, and is simple to use. But if you want to take logging seriously — and you should — this is not the way to achieve it.

开发人员倾向于依靠Node的console.log函数来记录应用程序事件,因为它易于访问,不需要额外的设置并且易于使用。 但是,如果您想认真对待日志并且应该这样做,那不是实现日志的方法。

console.log prints its output to stdout. Other console functions, like console.err and console.warn, print outputs to stderr. You can’t configure console.log to transport the logs to a file or a database. You can’t turn logging on and off or switch between different logging levels (which we will talk about later) when the app is in production.

console.log其输出打印到stdout 。 其他控制台功能(例如console.errconsole.warnstderr打印到stderr 。 您无法配置console.log将日志传输到文件或数据库。 当应用程序投入生产时,您将无法打开和关闭日志记录或在不同的日志记录级别之间切换(我们将在后面讨论)。

Simply put, console.log doesn’t provide enough features or configuration options to become an adequate logging tool. You should instead use a dedicated logging library to get the job done properly.

简而言之, console.log没有提供足够的功能或配置选项来成为足够的日志记录工具。 相反,您应该使用专用的日志记录库来正确完成工作。

2.使用专用的日志库 (2. Use a dedicated logging library)

A dedicated logging library, unlike console.log, provides a set of features to create logs that let us identify problems easily and enough configurations to make the best use of our logs.

console.log不同,专用的日志记录库提供了一组创建日志的功能,这些功能使我们可以轻松地确定问题,并进行了充分配置以充分利用日志。

  • Most logging libraries support several logging levels like info, debug, warning, and error. These levels help filter logs according to our needs.

    大多数日志记录库支持几种日志记录级别,例如信息,调试,警告和错误。 这些级别有助于根据我们的需求过滤日志。
  • The biggest advantage of using a logging library is being able to switch between logging levels even when the app is in production.

    使用日志记录库的最大优点是即使在应用程序处于生产状态时,也可以在日志记录级别之间进行切换。
  • They also support formatting logs with different colors for different levels of logs. Some libraries also support the formatting of different data types like JSON.

    它们还支持格式化具有不同颜色的日志,以用于不同级别的日志。 一些库还支持JSON等不同数据类型的格式。

Winston and Bunyan are two of the most popular logging libraries available to Node developers.

WinstonBunyan是Node开发人员可以使用的两个最受欢迎的日志记录库。

In this article, we are going to use Winston in the code examples.

在本文中,我们将在代码示例中使用Winston。

3.源,时间戳,上下文-日志中最重要的部分 (3. Source, timestamp, context — the most important parts of a log)

Every log recorded by your application should consist of these three parts.

您的应用程序记录的每个日志应由这三个部分组成。

  • Source: If we are debugging our application using the logs, it’s important to know where each event occurred. The source could be the name of the host, method, zone, or in microservices architecture, the name of the service.

    来源:如果我们正在使用日志调试应用程序,那么了解每个事件发生的位置很重要。 源可以是主机,方法,区域的名称,或者在微服务体系结构中可以是服务的名称。
  • Timestamp: Recording the timestamp of the events that occurred is also important to logging. We might need to filter the logs recorded within a certain timeframe or sort the logs by the time they occurred. Hence, the timestamp is an essential part of an application log.

    时间戳记:记录发生的事件的时间戳记对于日志记录也很重要。 我们可能需要过滤在特定时间范围内记录的日志,或者按发生时间对日志进行排序。 因此,时间戳是应用程序日志的重要组成部分。
  • Context and level: The context of a particular log is important when we are debugging the application. For example, if the application is registering a new user, there are several ways this operation could fail. The user might provide invalid data or could already be registered in the system. These failures are not occurring because our application is behaving faultily. But if this operation fails because the application couldn’t connect to the database, that signifies that something has gone wrong. Therefore, providing the context of the event with every log is crucial to make the best of logging. In addition, recording the level is also important to filter and identify different issues of the application based on how critical they are.

    上下文和级别:在调试应用程序时,特定日志的上下文很重要。 例如,如果应用程序正在注册新用户,则此操作可能会以几种方式失败。 用户可能提供了无效数据,或者可能已经在系统中注册。 由于我们的应用程序行为异常,因此不会发生这些故障。 但是,如果由于应用程序无法连接到数据库而导致此操作失败,则表明出现了问题。 因此,在每个日志中提供事件的上下文对于充分利用日志至关重要。 此外,记录级别对于根据应用程序的严重性来筛选和识别应用程序的不同问题也很重要。

4.正确使用日志级别 (4. Use log levels properly)

We use logging levels to sort them by urgency so that we can filter them accordingly.

我们使用日志记录级别按紧急程度对其进行排序,以便我们可以相应地对其进行过滤。

Syslog standard provides specified levels, declared according to their severity, that we can use when logging.

Syslog标准提供了指定的级别(根据严重性声明),我们可以在登录时使用这些级别。

  • Emergency: The system is unusable.

    紧急:系统无法使用。
  • Alert: Action must be taken immediately.

    警告:必须立即采取行动。
  • Critical: Critical conditions.

    严重:严重条件。
  • Error: Error conditions.

    错误:错误情况。
  • Warning: Warning conditions.

    警告:警告条件。
  • Notice: Normal but significant conditions.

    注意:正常但重要的条件。
  • Informational: Informational messages.

    信息性:信息性消息。
  • Debug: Debug-level messages.

    调试:调试级别的消息。

You can alter standard levels to create a list of levels that better suit your application. However, each log must be given a level to be able to filter them as required.

您可以更改标准级别以创建更适合您的应用程序的级别列表。 但是,必须为每个日志指定一个级别,以便能够根据需要过滤它们。

5.登录时不该做什么 (5. What not to do when logging)

Logging should not generate any errors of its own.

日志记录不应产生任何错误。

We are trying to find errors in our application with the logs. We don’t need logs to add their own errors on top of that. So, make sure that logging operations are written in a way that does not generate errors of its own.

我们正在尝试通过日志查找应用程序中的错误。 在此之上,我们不需要日志来添加自己的错误。 因此,确保以不会产生自身错误的方式编写日志记录操作。

For example, the following code could throw an error when logging. You should avoid instances like this:

例如,以下代码在记录时可能会引发错误。 您应该避免这样的实例:

const logger = require("../logger")
exports.findUserByUsername = async (req, res) => {
    logger.info(`Invoking findUserById with the id ${req.params.username}`)
    //implementation
    logger.debug(`Finding user data from the database ${userModel.find({username: req.params.username})}`) //could throw an error.
}

Logging operations should also be stateless.

日志记录操作也应该是无状态的。

Logging operations should not generate any state changes in the application, like changing the database. You should avoid scenarios like this:

日志记录操作不应在应用程序中生成任何状态更改,例如更改数据库。 您应该避免这样的情况:

exports.saveUser = async (req, res) => {
    logger.info("invoking saveUser()")
    //implementation
    logger.debug(`saving user to the database ${userModel.save(req.body)}`) //changes application state
}

6.在生产中使用适当的日志记录级别(6. Use the appropriate logging level in production)

Being able to log records of every level would be ideal when our app is in production. But it’s not always practical. If your application has heavy user traffic, logging every level of code would result in a huge performance dip.

当我们的应用程序投入生产时,能够记录每个级别的记录将是理想的选择。 但这并不总是实用的。 如果您的应用程序有大量的用户流量,则记录每个级别的代码都会导致性能下降。

We need to take a proactive approach to avoid this and log optimally. In a production-level application, the majority of the logs belong to the debug and info levels. So during the normal runtime, if we turn off debug and info logs, and log only the lower levels, we can avoid the performance issues that come with frequent logging.

我们需要采取积极主动的方法来避免这种情况并以最佳方式记录日志。 在生产级应用程序中,大多数日志属于调试和信息级别。 因此,在正常运行时,如果我们关闭调试和信息日志,并且仅记录较低级别的日志,则可以避免频繁记录所带来的性能问题。

In an application in production, we turn on the warning, error, and other lower levels of logs to identify if it is in critical status. We can turn on debug- and info-level logs only when an error is detected.

在生产中的应用程序中,我们打开警告,错误和其他较低级别的日志,以识别日志是否处于严重状态。 仅当检测到错误时,我们才能打开调试和信息级别的日志。

One of the benefits of using a logging framework is being able to change the logging level easily while in production.

使用日志记录框架的好处之一是能够在生产中轻松更改日志记录级别。

7.将当前日志记录级别存储为环境变量 (7. Store the current logging level as an environment variable)

To ensure that we can easily change between levels when needed, you should store the current logging level of the application as an environment variable. This gives us the ability to change the level when the application is still in production by simply changing the variable value.

为了确保我们可以在需要时轻松地在级别之间进行更改,您应该将应用程序的当前日志记录级别存储为环境变量。 这使我们能够通过简单地更改变量值来在应用程序仍处于生产状态时更改级别。

//.en.
LOG_LEVEL = "warn"




//logger.js
const transports = {
  console: new winston.transports.Console({ level: process.env.LOG_LEVEL}),
};
const logger = winston.createLogger({
  transports: [
    Transports.console,
 ]
});

概要(Summary)

If you are building an application that is intended to go to production, logging is a crucial feature it should have. In this article, we discussed the best practices you should use when creating a logging system. With this knowledge, you can start building a great logging system for your application today.

如果要构建要用于生产的应用程序,则日志记录是它应具有的关键功能。 在本文中,我们讨论了在创建日志记录系统时应使用的最佳实践。 有了这些知识,您就可以立即为您的应用程序构建出色的日志记录系统。

Thanks for reading!

谢谢阅读!

翻译自: https://medium.com/better-programming/you-built-your-node-app-but-are-you-logging-665c7b2bb06b

jenkins 构建节点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值