morgan node js для чего
Morgan node js для чего
HTTP request logger middleware for node.js
Named after Dexter, a show you should not watch until completion.
Using a predefined format string
Using format string of predefined tokens
Using a custom format function
Morgan accepts these properties in the options object.
Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data from the response (like the response code, content length, etc.) cannot be logged.
There are various pre-defined formats provided:
Standard Apache combined log output.
Standard Apache common log output.
Concise output colored by response status for development use. The :status token will be colored green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for information codes.
Shorter than default, also including response time.
The minimal output.
Creating new tokens
To define a token, simply invoke morgan.token() with the name and a callback function. This callback function is expected to return a string value. The value returned is then available as «:type» in this case:
Calling morgan.token() using the same name as an existing token will overwrite that token definition.
The current date and time in UTC. The available formats are:
The HTTP version of the request.
The HTTP method of the request.
The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
The user authenticated as part of Basic auth for the request.
The given header of the request. If the header is not present, the value will be displayed as «-» in the log.
The given header of the response. If the header is not present, the value will be displayed as «-» in the log.
The time between the request coming into morgan and when the response headers are written, in milliseconds.
The status code of the response.
If the request/response cycle completes before a response was sent to the client (for example, the TCP socket closed prematurely by a client aborting the request), then the status will be empty (displayed as «-» in the log).
The time between the request coming into morgan and when the response has finished being written out to the connection, in milliseconds.
The contents of the User-Agent header of the request.
Simple app that will log all request in the Apache combined format to STDOUT
vanilla http server
Simple app that will log all request in the Apache combined format to STDOUT
write logs to a file
Simple app that will log all requests in the Apache combined format to one log file per day in the log/ directory using the rotating-file-stream module.
split / dual logging
The morgan middleware can be used as many times as needed, enabling combinations like:
Sample app that will log all requests to a file using Apache format, but error responses are logged to the console:
use custom token formats
Sample app that will use custom token formats. This adds an ID to all requests and displays it using the :id token.
О логгировании в Node.js
Зачем надо логгировать
Вы запустили серверное приложение у которого нету GUI для отображения своего состояния, а знать очень хочется. Самое простое и очевидное решение, выводить какие то сообщения куда то — stdout/stderr, файлики, syslog, что-то более извращенное. Это и есть логирование (спасибо кэп).
Перечислю основные задачи, которые могут решаться при помощи логгирования:
Как логгировать
Писать в логи надо и много и мало. Настолько мало, чтобы понять в каком состоянии приложение сейчас, и настолько много, чтобы если приложение рухнуло понять почему.
То есть пишем, что вы сами считаете нужным, для того, чтобы вам было понятно, что происходит. Но надо подчеркнуть, что логгирование ест ресурсы приложения — так что не надо увлекаться, я видел приложение однажды, где логгирование жрало примерно 50% производительности (это конечно же ппц не надо так делать).
Если происходит ошибка/исключение и тд, вам нужно понять почему. В этот самый момент, пишем в логи все (да, абсолютно все), что необходимо для понимания, почему это случилось (здесь как раз надо писать много — не надо скромничать).
Уровни логов
Очевидно, что не всякое сообщение имеет одинаковую важность. Обычно большинству приложении достаточно 5 уровней логгов — я использую название уровней к которым привык с slf4j:
Далее будут небольшое сравнение логгеров, которые я опробовал в node.js и что в них не так, с учетом написанного выше.
log4js
Это первое на что я посмотрел, в надежде что это хоть сколько нибудь будет похоже на log4j.
В консоли появится цветное сообщение:
В этом логгере есть необходимый минимум. Есть фильтрация сообщений по уровню и категории (имени логгера), время сообщения и возможность его изменить. Для вывода сообщений использутся util.format — поэтому поддерживаются те же опции форматирования, что и в console.log.
winston
Его часто рекомендуют на SO. Я лично ни кому бы его не рекомендовал.
Пример:
Что будет в консоли:
В этом месте был небольшой опус о том, что winston не позволяет выдавать время записей, благодаря Keenn, оказалось, что все таки можно, но эти опции (timestamp: true у транспортов) выключены по умолчанию, что очень странно.
bunyan
intel
При вот таком формате сообщений ‘[%date] %logger:: %message’, который разумно ожидать всегда. Попробуем заменить на стандартное сообщение в intel, чтобы ощутить всю мощь оптимизаций:
Интересное изменение.
Вообщем, то все. Если кому интересно — форк (я скорее всего не буду принимать feature запросы, так как писал для себя в свободное время, с багами и пулл реквестами добро пожаловать).
Как всегда, надеюсь в комментариях найти что-то новое для себя. Ошибки пожалуйста в личку.
Morgan node js для чего
HTTP request logger middleware for node.js
Named after Dexter, a show you should not watch until completion.
This is a Node.js module available through the npm registry. Installation is done using the npm install command:
Using a predefined format string
Using format string of predefined tokens
Using a custom format function
Morgan accepts these properties in the options object.
Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data from the response (like the response code, content length, etc.) cannot be logged.
There are various pre-defined formats provided:
Standard Apache combined log output.
Standard Apache common log output.
Concise output colored by response status for development use. The :status token will be colored green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for information codes.
Shorter than default, also including response time.
The minimal output.
Creating new tokens
To define a token, simply invoke morgan.token() with the name and a callback function. This callback function is expected to return a string value. The value returned is then available as «:type» in this case:
Calling morgan.token() using the same name as an existing token will overwrite that token definition.
The current date and time in UTC. The available formats are:
The HTTP version of the request.
The HTTP method of the request.
The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.
The user authenticated as part of Basic auth for the request.
The given header of the request. If the header is not present, the value will be displayed as «-» in the log.
The given header of the response. If the header is not present, the value will be displayed as «-» in the log.
The time between the request coming into morgan and when the response headers are written, in milliseconds.
The status code of the response.
If the request/response cycle completes before a response was sent to the client (for example, the TCP socket closed prematurely by a client aborting the request), then the status will be empty (displayed as «-» in the log).
The time between the request coming into morgan and when the response has finished being written out to the connection, in milliseconds.
The contents of the User-Agent header of the request.
Sample app that will log all request in the Apache combined format to STDOUT
vanilla http server
Sample app that will log all request in the Apache combined format to STDOUT
write logs to a file
Sample app that will log all requests in the Apache combined format to one log file per day in the log/ directory using the rotating-file-stream module.
split / dual logging
The morgan middleware can be used as many times as needed, enabling combinations like:
Sample app that will log all requests to a file using Apache format, but error responses are logged to the console:
use custom token formats
Sample app that will use custom token formats. This adds an ID to all requests and displays it using the :id token.
Руководство по логированию в Node.js
В этой статье рассматриваются различные ситуации, в которых требуется вести логи; показывается разница между методами console.log и console.error в Node.js и демонстрируется, как передать функцию логирования библиотекам, не перегружая пользовательскую консоль.
Теоретические основы работы с Node.js
Когда необходимо записывать события в журнал?
Теперь, рассмотрев технические аспекты, лежащие в основе записи в журнал, перейдём к различным сценариям, в которых необходимо регистрировать события. Обычно эти сценарии относятся к одной из нескольких категорий:
Ведение журналов для серверных приложений
Существует несколько причин для логирования событий, происходящих на сервере. Например, логирование входящих запросов позволяет получить статистические данные о том, как часто пользователи сталкиваются с ошибкой 404, что может быть этому причиной или какое клиентское приложение User-Agent используется. Также можно узнать время возникновения ошибки и её причину.
Для того чтобы поэкспериментировать с материалом, приведённым в этой части статьи, нужно создать новый каталог для проекта. В каталоге проекта создаём index.js для кода, который будет использоваться, и выполняем следующие команды для запуска проекта и установки express :
Здесь используется console.log(‘%O’, req) для регистрации целого объекта в журнале. С точки зрения внутренней структуры метод console.log применяет util.forma t, который кроме %O поддерживает и другие метки-заполнители. Информацию о них можно найти в документации Node.js.
При выполнении node index.js для запуска сервера и переходе на localhost:3000 в консоли отображается много ненужной информации:
Можно написать собственную функцию логирования, которая будет выводить только нужные данные, однако сначала следует определиться, какая именно информация необходима. Несмотря на то, что в центре внимания обычно оказывается содержание сообщения, в реальности часто необходимо получить дополнительную информацию, которая включает:
Этого можно добиться, получив доступ к разным частям процесса process и написав несколько строчек кода на JavaScript. Однако Node.js замечателен тем, что в нём уже есть экосистема npm и несколько библиотек, которые можно использовать для этих целей. К ним относятся:
Установим pino и express-pino-logger :
В документе также говорится о ротации файлов журнала, фильтрации и записи данных журнала в другие файлы.
Ведение журналов для библиотек
Изучив способы эффективной организации ведения журналов для серверных приложений, можно использовать ту же технологию для собственных библиотек.
Проблема в том, что в случае с библиотекой может понадобиться вести журнал в целях отладки, не нагружая при этом приложения клиента. Наоборот, клиент должен иметь возможность активировать журнал, если необходимо произвести отладку. По умолчанию библиотека не должна производить записи выходных данных, предоставив это право пользователю.
Если применить эту команду к существующему приложению, можно увидеть множество дополнительных выходных данных, которые помогут при отладке:
Создайте новый файл под названием random-id.j s, который будет моделировать работу библиотеки, и поместите в него следующий код:
В результате записи журнала отладки библиотеки отобразятся так же, как и в журнале приложения:
Выходные данные интерфейса командной строки (CLI)
Создавая интерфейс командной строки с помощью Node.js, можно добавить различные цвета, блоки с изменяемым значением или инструменты форматирования, чтобы придать интерфейсу визуально привлекательный вид. Однако при этом нужно держать в уме несколько сценариев.
Значения могут различаться для каждого из трёх потоков в зависимости от того, как были запущены процессы Node.js. Подробную информацию об этом можно найти в документации Node.js, в разделе «Ввод/вывод процессов».
После этого повторно выполняем команду, но перенаправляем выходные данные в файл, а затем просматриваем содержимое:
Заключение
Начать использовать JavaScript и внести первую строчку в журнал консоли с помощью console.log довольно просто. Но перед тем как развернуть код в продакшене, следует учесть несколько аспектов использования журнала. Данная статья является лишь введением в различные способы и решения, применяемые при организации журнала событий. Она не содержит всего, что вам необходимо знать. Поэтому рекомендуется обращать внимание на удачные проекты с открытым кодом и отслеживать, каким образом в них решена проблема логирования и какие инструменты используются при этом. А теперь попробуйте сами вести логи без вывода данных в консоль.
Если вы знаете другие инструменты, о которых стоит упомянуть, напишите о них в комментариях.
How To Use morgan in Your Express Project
By Cooper Makhijani
Last Validated on December 24, 2020 Originally Published on July 20, 2019
Introduction
morgan is a Node.js and Express middleware to log HTTP requests and errors, and simplifies the process. In Node.js and Express, middleware is a function that has access to the request and response lifecycle methods, and the next() method to continue logic in your Express server.
In this article you will explore how to implement morgan in your Express project.
Prerequisites
To follow along with this article, you will need:
Step 1 – Setting Up the Project
As Express.js is a Node.js framework, ensure you have the latest version of Node.js from Node.js before moving forward.
To include morgan in your Express project, you will need to install it as a dependency.
Create a new directory named express-morgan for your project:
Change into the new directory:
Initialize a new Node project with defaults. This will include your package.json file to access your dependencies:
Install morgan as a dependency:
Now that you’ve added morgan to your project, let’s include it in your Express server. In your index.js file, instantiate an Express instance and require morgan :
With your Express server now set up, let’s look at using morgan to add request logging.
Step 2 – Using morgan in Express
In your index.js file, invoke the app.use() Express middleware and pass morgan() as an argument:
Including the preset tiny as an argument to morgan() will use its built-in method, identify the URL, declare a status, and the request’s response time in milliseconds.
Alternatively, morgan reads presets like tiny in a format string defined below:
This tends to the same functionality contained in the tiny preset in a format that morgan parses. Following the : symbol are morgan functions called tokens. You can use the format string to define tokens create your own custom morgan middleware.
Step 3 – Creating Your Own Tokens
The anonymous callback function will return the hostname on the req object as a new token to use in an HTTP request in your Express server.
Step 4 – Designing Tokens with Custom Arguments
To denote custom arguments, you can use square brackets to define arguments passed to a token. This will allow your tokens to accept additional arguments. In your index.js file apply a custom argument to the morgan format string in the :param token:
Conclusion
morgan allows flexibility when logging HTTP requests and updates precise status and response time in custom format strings or in presets. For further reading, check out the morgan documentation.