The post has been translated automatically. Original language: Russian
At three o'clock in the morning, an alert arrives to the attendant: the issuance of loans has stopped. He opens the logs, and there are a thousand lines of "Request failed" — without an application number, without a service name, without a reason. Whether he would find it in ten minutes or would wait until morning was decided long before the crash — when the developer was writing this line.
The log is a log of system events.: what happened, when, with which object, and how it ended. Below are the rules that we adhere to when accompanying financial systems.
We run a single identifier through all services
The request identifier (correlation id) is a label that the client's operation receives at the entrance and carries with it further. The loan application goes through a questionnaire, checks, calculation of the solution, contract, payment — and the records of each service have the same label. Without it, a failure in the chain of five services is searched for hours, comparing records by time. With her, one search is enough: the entire path of the operation is in front of your eyes.
We write the context: object, action, result, time
Each line answers four questions: what did you work with, what did you do, how did it end, and how long did it take. We call the object the internal number of the application or contract — the client's name and phone number do not belong here.
Badly:
ERROR Request failed
Well:
ERROR request_id=7f3a9c application_id=184502 action=disbursement result=failed reason=bank_timeout duration_ms=30012
The second line is written in a structured format: this is a set of fields, not free text. These logs can be used to search and filter: all payment errors in the last hour, all transactions longer than five seconds.
We explain the error in clear words
"Error 500" and "something went wrong" do not help the attendant. A good message tells you what you tried to do, what you received, and what it means: "The payment could not be sent: the bank did not respond in 30 seconds, the request was returned to the queue, and it will be repeated in 5 minutes." After reading it, a person understands whether it is necessary to intervene.
We agree on the levels in advance. Error — operation failed. Warning — completed, but on the second attempt or slower than usual. Information is the key steps of the process. Debugging is the details for the developer; it is turned off in the production system, it is turned on during the analysis.
We measure each call to an external service
Time is most often "lost" at the border of the system: payment gateway, government database, SMS distribution. For each call, we write where we contacted, how long we waited, and what response code we received. Then the question "are we slowing down or are they slowing down" is answered by the log, and a late-night chat argument is not needed.
We don't write secrets, we mask personal data.
They don't get into the log:
- passwords, tokens, API keys, SMS confirmation codes;
- full card numbers, IIN, phone numbers, passport data — only in disguise or in no way;
- The request and response bodies are "as is": they almost always contain personal data;
- secrets in addresses (URLs): The web server writes the address to its log automatically, along with the token in the parameters.
If the recording is meaningless without a card or phone, we leave the last four digits.:
INFO request_id=7f3a9c application_id=184502 action=card_check card=****9012 phone=***4567 result=ok
Why is it so strict? Logs are read by more people than the database; they are copied to third-party systems, stored longer, and protected less well. And the requirements of the law on personal data also apply to journals: the IIN in the log is the same personal data as the IIN in the database.
We decide who reads the logs and how much to store them.
Three questions worth answering before launching. How long to store: the deadline is set explicitly, after which the records are deleted. Who has access: those who need it for work, not the entire team by default. Who receives error alerts: a specific person on duty — everyone will see the message in the general chat and no one will understand it.
And the rule for the team is: we check the logs for a code review (when a colleague reads the changes before the release) just like the code itself. Is there a request ID, is the error message clear, and is the client's phone number missing?
A good log is a note to the person on duty who doesn't know anything about your task at three in the morning. It has everything to find the reason, and there is nothing that cannot be shown to an outsider.
And which line in the log saved you once, or didn't it turn up when you needed it most?
Три часа ночи, дежурному приходит оповещение: выдача кредитов остановилась. Он открывает логи, а там тысяча строк «Request failed» — без номера заявки, без названия сервиса, без причины. Найдёт ли он её за десять минут или будет гадать до утра, решилось задолго до сбоя — когда разработчик писал эту строку.
Лог — это журнал событий системы: что произошло, когда, с каким объектом и чем закончилось. Ниже — правила, которых мы держимся, сопровождая финансовые системы.
Проводим один идентификатор через все сервисы
Идентификатор запроса (correlation id) — метка, которую операция клиента получает на входе и несёт с собой дальше. Заявка на кредит проходит анкету, проверки, расчёт решения, договор, выплату — и в записях каждого сервиса стоит одна и та же метка. Без неё сбой в цепочке из пяти сервисов ищут часами, сопоставляя записи по времени. С ней хватает одного поиска: весь путь операции перед глазами.
Пишем контекст: объект, действие, результат, время
Каждая строка отвечает на четыре вопроса: с чем работали, что делали, чем закончилось, сколько это заняло. Объект называем внутренним номером заявки или договора — фамилии и телефону клиента здесь не место.
Плохо:
ERROR Request failed
Хорошо:
ERROR request_id=7f3a9c application_id=184502 action=disbursement result=failed reason=bank_timeout duration_ms=30012
Вторая строка записана в структурированном формате: это набор полей, а не свободный текст. По таким логам можно искать и фильтровать: все ошибки выплаты за последний час, все операции дольше пяти секунд.
Объясняем ошибку понятными словами
«Error 500» и «что-то пошло не так» дежурному не помогают. Хорошее сообщение говорит, что пытались сделать, что получили и что это значит: «Не удалось отправить выплату: банк не ответил за 30 секунд, заявка возвращена в очередь, повтор через 5 минут». Прочитав его, человек понимает, нужно ли вмешиваться.
Об уровнях договариваемся заранее. Ошибка — операция не выполнена. Предупреждение — выполнена, но со второй попытки или медленнее обычного. Информация — ключевые шаги процесса. Отладка — подробности для разработчика; в рабочей системе она выключена, её включают на время разбора.
Замеряем каждый вызов внешнего сервиса
Время чаще всего «теряется» на границе системы: платёжный шлюз, государственная база, рассылка SMS. Для каждого вызова пишем, куда обращались, сколько ждали и какой код ответа получили. Тогда на вопрос «тормозим мы или они» отвечает лог, и ночной спор в чате не нужен.
Не пишем секреты, маскируем персональные данные
В лог не попадают:
- пароли, токены, ключи API, коды подтверждения из SMS;
- номера карт целиком, ИИН, телефоны, паспортные данные — только в маскированном виде или никак;
- тела запросов и ответов «как есть»: в них почти всегда оказываются персональные данные;
- секреты в адресах (URL): веб-сервер записывает адрес в свой лог автоматически, вместе с токеном в параметрах.
Если без карты или телефона запись теряет смысл, оставляем последние четыре цифры:
INFO request_id=7f3a9c application_id=184502 action=card_check card=****9012 phone=***4567 result=ok
Почему так строго? Логи читают больше людей, чем базу данных; их копируют в сторонние системы, хранят дольше и защищают слабее. А требования закона о персональных данных действуют и для журналов: ИИН в логе — такие же персональные данные, как ИИН в базе.
Решаем, кто читает логи и сколько их хранить
Три вопроса, на которые стоит ответить до запуска. Сколько хранить: срок задан явно, после него записи удаляются. У кого доступ: у тех, кому он нужен для работы, а не у всей команды по умолчанию. Кто получает оповещения об ошибках: конкретный дежурный — в общем чате сообщение увидят все и не разберёт никто.
И правило для команды: проверяем логи на ревью кода (когда изменения перед выпуском читает коллега) так же, как сам код. Есть ли идентификатор запроса, понятно ли сообщение об ошибке, не попал ли в строку телефон клиента.
Хороший лог — это записка дежурному, который в три часа ночи ничего не знает о вашей задаче. В ней есть всё, чтобы найти причину, и нет ничего, что нельзя показать постороннему.
А какая строка в логе однажды спасла вас — или не нашлась, когда была нужнее всего?
Comments 0
Newest Popular