File
Blob: src/workerd/server/json-logger.h
| 1 | // Copyright (c) 2017-2022 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | #pragma once |
| 6 | |
| 7 | #include <kj/exception.h> |
| 8 | #include <kj/function.h> |
| 9 | #include <kj/main.h> |
| 10 | #include <kj/string.h> |
| 11 | |
| 12 | namespace workerd::server { |
| 13 | |
| 14 | class JsonLogger: public kj::ExceptionCallback { |
| 15 | public: |
| 16 | void logMessage(kj::LogSeverity severity, |
| 17 | const char* file, |
| 18 | int line, |
| 19 | int contextDepth, |
| 20 | kj::String&& text) override; |
| 21 | |
| 22 | kj::Function<void(kj::Function<void()>)> getThreadInitializer() override; |
| 23 | |
| 24 | StackTraceMode stackTraceMode() override { |
| 25 | return StackTraceMode::ADDRESS_ONLY; |
| 26 | } |
| 27 | |
| 28 | private: |
| 29 | bool loggingInProgress = false; |
| 30 | }; |
| 31 | |
| 32 | class StructuredLoggingProcessContext final: public kj::ProcessContext { |
| 33 | // A ProcessContext implementation that supports both plain text and structured JSON logging. |
| 34 | // This context wraps TopLevelProcessContext and adds the ability to emit log messages in |
| 35 | // JSON format when structured logging is enabled. |
| 36 | |
| 37 | public: |
| 38 | explicit StructuredLoggingProcessContext(kj::StringPtr programName); |
| 39 | |
| 40 | // Enable structured JSON logging. This can only be called once and cannot be reversed. |
| 41 | // When enabled: Log messages are formatted as JSON and sent to stdout or stderr |
| 42 | // This also enables an ExceptionCallback to replace KJ_LOGs with structured logs. |
| 43 | // To reduce code duplication from TopLevelProcessContext, while JsonLogger sends |
| 44 | // all logs to stdout, StructuredLoggingProcessContext sends all to the fd that |
| 45 | // TopLevelProcessContext would have sent to. |
| 46 | // When disabled: Log messages are sent as plain text to stdout or stderr (like |
| 47 | // TopLevelProcessContext) |
| 48 | void enableStructuredLogging(); |
| 49 | |
| 50 | kj::StringPtr getProgramName() override; |
| 51 | KJ_NORETURN(void exit() override); |
| 52 | void warning(kj::StringPtr message) const override; |
| 53 | void error(kj::StringPtr message) const override; |
| 54 | KJ_NORETURN(void exitError(kj::StringPtr message) override); |
| 55 | KJ_NORETURN(void exitInfo(kj::StringPtr message) override); |
| 56 | void increaseLoggingVerbosity() override; |
| 57 | |
| 58 | private: |
| 59 | kj::TopLevelProcessContext topLevelContext; |
| 60 | kj::Maybe<JsonLogger> jsonLogger; |
| 61 | bool useStructuredLogging = false; |
| 62 | }; |
| 63 | |
| 64 | } // namespace workerd::server |