Skip to content
Kong Summit 2022: Where API Innovation Runs Wild  —Learn More →
Kong Logo | Kong Docs Logo
search
  • We're Hiring!
  • Docs
    • Kong Gateway
    • Konnect Cloud
    • Kong Mesh
    • Plugin Hub
    • decK
    • Kubernetes Ingress Controller
    • Insomnia
    • Kuma

    • Kong Konnect Platform

    • Docs contribution guidelines
  • Plugin Hub
  • Support
  • Community
  • Kong Academy
Request Demo
  • Kong Gateway
  • Konnect Cloud
  • Kong Mesh
  • Plugin Hub
  • decK
  • Kubernetes Ingress Controller
  • Insomnia
  • Kuma

  • Kong Konnect Platform

  • Docs contribution guidelines
  • 2.8.x (latest)
  • 2.7.x
  • 2.6.x
  • Older Enterprise versions (0.31-2.5)
  • Older OSS versions (0.13-2.5)
  • Archive (pre-0.13)
    • Version Support Policy
    • Changelog
    • Kubernetes
    • Helm
    • OpenShift with Helm
    • Docker
    • Amazon Linux
    • CentOS
    • macOS
    • Debian
    • RHEL
    • Ubuntu
    • Migrating from OSS to EE
    • Upgrade Kong Gateway
    • Upgrade Kong Gateway OSS
      • Configuring a Service
      • Configuring a gRPC Service
      • Enabling Plugins
      • Adding Consumers
      • Prepare to Administer
      • Expose your Services
      • Protect your Services
      • Improve Performance
      • Secure Services
      • Set Up Intelligent Load Balancing
      • Manage Administrative Teams
      • Publish, Locate, and Consume Services
    • Running Kong as a Non-Root User
    • Resource Sizing Guidelines
      • Deploy Kong Gateway in Hybrid Mode
    • Kubernetes Deployment Options
    • Control Kong Gateway through systemd
    • Performance Testing Framework
    • DNS Considerations
    • Default Ports
      • Access Your License
      • Deploy Your License
      • Monitor License Usage
      • Start Kong Gateway Securely
      • Keyring and Data Encryption
      • Kong Security Update Process
      • Authentication Reference
        • OpenID Connect with Curity
        • OpenID Connect with Azure AD
        • OpenID Connect with Google
        • OpenID Connect with Okta
        • OpenID Connect with Auth0
        • OpenID Connect with Cognito
        • OpenID Connect Plugin Reference
      • Allowing Multiple Authentication Methods
        • Create a Super Admin
        • Configure Networking
        • Configure Kong Manager to Send Email
        • Reset Passwords and RBAC Tokens
        • Configure Workspaces
        • Basic Auth
        • LDAP
        • OIDC
        • Sessions
        • Add a Role
        • Add a User
        • Add an Admin
      • Mapping LDAP Service Directory Groups to Kong Roles
      • Enable the Dev Portal
      • Structure and File Types
      • Portal API
      • Working with Templates
      • Using the Editor
          • Basic Auth
          • Key Auth
          • OIDC
          • Sessions
          • Adding Custom Registration Fields
        • SMTP
        • Workspaces
        • Manage Developers
        • Developer Roles and Content Permissions
          • Authorization Provider Strategy
          • Enable Application Registration
          • Enable Key Authentication for Application Registration
          • External OAuth2 Support
          • Set up Okta and Kong for external OAuth
          • Set Up Azure AD and Kong for External Authentication
          • Manage Applications
        • Easy Theme Editing
        • Migrating Templates Between Workspaces
        • Markdown Rendering Module
        • Customizing Portal Emails
        • Adding and Using JavaScript Assets
        • Single Page App in Dev Portal
        • Alternate OpenAPI Renderer
      • Helpers CLI
    • Configure gRPC Plugins
    • GraphQL Quickstart
    • Logging Reference
    • Network and Firewall
      • Metrics
      • Reports
      • Vitals with InfluxDB
      • Vitals with Prometheus
      • Estimate Vitals Storage in PostgreSQL
    • Prometheus plugin
    • Zipkin plugin
      • DB-less Mode
      • Declarative Configuration
      • Supported Content Types
      • Information Routes
      • Health Routes
      • Tags
      • Service Object
      • Route Object
      • Consumer Object
      • Plugin Object
      • Certificate Object
      • CA Certificate Object
      • SNI Object
      • Upstream Object
      • Target Object
        • Licenses Reference
        • Licenses Examples
        • Workspaces Reference
        • Workspace Examples
        • RBAC Reference
        • RBAC Examples
        • API Reference
        • Examples
        • API Reference
        • Examples
        • Event Hooks Reference
        • Examples
      • Audit Logging
      • Keyring and Data Encryption
      • Securing the Admin API
    • DB-less and Declarative Configuration
    • Configuration Reference
    • CLI Reference
    • Load Balancing Reference
    • Proxy Reference
    • Rate Limiting Library
    • Health Checks and Circuit Breakers Reference
    • Clustering Reference
      • kong.client
      • kong.client.tls
      • kong.cluster
      • kong.ctx
      • kong.ip
      • kong.log
      • kong.nginx
      • kong.node
      • kong.request
      • kong.response
      • kong.router
      • kong.service
      • kong.service.request
      • kong.service.response
      • kong.table
      • Introduction
      • File structure
      • Implementing custom logic
      • Plugin configuration
      • Accessing the datastore
      • Storing custom entities
      • Caching custom entities
      • Extending the Admin API
      • Writing tests
      • (un)Installing your plugin
    • Plugins in Other Languages

github-edit-pageEdit this page

report-issueReport an issue

enterprise-switcher-iconSwitch to OSS

On this page
  • kong.log
    • kong.log(…)
    • kong.log.LEVEL(…)
    • kong.log.deprecation(…)
    • kong.log.inspect(…)
    • kong.log.inspect.on()
    • kong.log.inspect.off()
    • kong.log.set_serialize_value(key, value, options)
    • kong.log.serialize()
Kong Gateway
2.7.x
  • Home
  • Kong Gateway
  • Pdk
You are browsing documentation for an outdated version. See the latest documentation here.

kong.log

kong.log

This namespace contains an instance of a “logging facility”, which is a table containing all of the methods described below.

This instance is namespaced per plugin, and Kong will make sure that before executing a plugin, it will swap this instance with a logging facility dedicated to the plugin. This allows the logs to be prefixed with the plugin’s name for debugging purposes.

kong.log(…)

Write a log line to the location specified by the current Nginx configuration block’s error_log directive, with the notice level (similar to print()).

The Nginx error_log directive is set via the log_level, proxy_error_log and admin_error_log Kong configuration properties.

Arguments given to this function will be concatenated similarly to ngx.log(), and the log line will report the Lua file and line number from which it was invoked. Unlike ngx.log(), this function will prefix error messages with [kong] instead of [lua].

Arguments given to this function can be of any type, but table arguments will be converted to strings via tostring (thus potentially calling a table’s __tostring metamethod if set). This behavior differs from ngx.log() (which only accepts table arguments if they define the __tostring metamethod) with the intent to simplify its usage and be more forgiving and intuitive.

Produced log lines have the following format when logging is invoked from within the core:

 [kong] %file_src:%line_src %message

In comparison, log lines produced by plugins have the following format:

 [kong] %file_src:%line_src [%namespace] %message

Where:

  • %namespace: is the configured namespace (the plugin name in this case).
  • %file_src: is the file name from where the log was called from.
  • %line_src: is the line number from where the log was called from.
  • %message: is the message, made of concatenated arguments given by the caller.

For example, the following call:

 kong.log("hello ", "world")

would, within the core, produce a log line similar to:

 2017/07/09 19:36:25 [notice] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"

If invoked from within a plugin (e.g. key-auth) it would include the namespace prefix, like so:

 2017/07/09 19:36:25 [notice] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"

Phases

  • init_worker, certificate, rewrite, access, header_filter, response, body_filter, log

Parameters

  • … : all params will be concatenated and stringified before being sent to the log

Returns

  • Nothing; throws an error on invalid inputs.

Usage

kong.log("hello ", "world") -- alias to kong.log.notice()

Back to top

kong.log.LEVEL(…)

Similar to kong.log(), but the produced log will have the severity given by <level>, instead of notice. The supported levels are:

  • kong.log.alert()
  • kong.log.crit()
  • kong.log.err()
  • kong.log.warn()
  • kong.log.notice()
  • kong.log.info()
  • kong.log.debug()

Logs have the same format as that of kong.log(). For example, the following call:

  kong.log.err("hello ", "world")

would, within the core, produce a log line similar to:

 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"

If invoked from within a plugin (e.g. key-auth) it would include the namespace prefix, like so:

 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"

Phases

  • init_worker, certificate, rewrite, access, header_filter, response, body_filter, log

Parameters

  • … : all params will be concatenated and stringified before being sent to the log

Returns

  • Nothing; throws an error on invalid inputs.

Usage

kong.log.warn("something require attention")
kong.log.err("something failed: ", err)
kong.log.alert("something requires immediate action")

Back to top

kong.log.deprecation(…)

Write a deprecation log line (similar to kong.log.warn).

Arguments given to this function can be of any type, but table arguments will be converted to strings via tostring (thus potentially calling a table’s __tostring metamethod if set). When the last argument is a table, it is considered as a deprecation metadata. The table can include following properties:

 {
   after = "2.5.0",   -- deprecated after Kong version 2.5.0 (defaults to `nil`)
   removal = "3.0.0", -- about to be removed with Kong version 3.0.0 (defaults to `nil`)
   trace = true,      -- writes stack trace along with the deprecation message (defaults to `nil`)
 }

For example, the following call:

 kong.log.deprecation("hello ", "world")

would, within the core, produce a log line similar to:

 2017/07/09 19:36:25 [warn] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"

If invoked from within a plugin (e.g. key-auth) it would include the namespace prefix, like so:

 2017/07/09 19:36:25 [warn] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"

And with metatable, the following call:

 kong.log.deprecation("hello ", "world", { after = "2.5.0", removal = "3.0.0" })

would, within the core, produce a log line similar to:

 2017/07/09 19:36:25 [warn] 25932#0: *1 [kong] some_file.lua:54 hello world (deprecated after 2.5.0, scheduled for removal in 3.0.0), client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"

Phases

  • init_worker, certificate, rewrite, access, header_filter, response, body_filter, log

Parameters

  • … : all params will be concatenated and stringified before being sent to the log (if the last param is a table, it is considered as a deprecation metadata)

Returns

  • Nothing; throws an error on invalid inputs.

Usage

kong.log.deprecation("hello ", "world")
kong.log.deprecation("hello ", "world", { after = "2.5.0" })
kong.log.deprecation("hello ", "world", { removal = "3.0.0" })
kong.log.deprecation("hello ", "world", { after = "2.5.0", removal = "3.0.0" })
kong.log.deprecation("hello ", "world", { trace = true })

Back to top

kong.log.inspect(…)

Like kong.log(), this function will produce a log with the notice level, and accepts any number of arguments as well. If inspect logging is disabled via kong.log.inspect.off(), then this function prints nothing, and is aliased to a “NOP” function in order to save CPU cycles.

This function differs from kong.log() in the sense that arguments will be concatenated with a space(" "), and each argument will be “pretty-printed”:

  • numbers will printed (e.g. 5 -> "5")
  • strings will be quoted (e.g. "hi" -> '"hi"')
  • array-like tables will be rendered (e.g. {1,2,3} -> "{1, 2, 3}")
  • dictionary-like tables will be rendered on multiple lines

This function is intended for use with debugging purposes in mind, and usage in production code paths should be avoided due to the expensive formatting operations it can perform. Existing statements can be left in production code but nopped by calling kong.log.inspect.off().

When writing logs, kong.log.inspect() always uses its own format, defined as:

 %file_src:%func_name:%line_src %message

Where:

  • %file_src: is the file name from where the log was called from.
  • %func_name: is the name of the function from where the log was called from.
  • %line_src: is the line number from where the log was called from.
  • %message: is the message, made of concatenated, pretty-printed arguments given by the caller.

This function uses the inspect.lua library to pretty-print its arguments.

Phases

  • init_worker, certificate, rewrite, access, header_filter, response, body_filter, log

Parameters

  • … : Parameters will be concatenated with spaces between them and rendered as described

Usage

kong.log.inspect("some value", a_variable)

Back to top

kong.log.inspect.on()

Enables inspect logs for this logging facility. Calls to kong.log.inspect will be writing log lines with the appropriate formatting of arguments.

Phases

  • init_worker, certificate, rewrite, access, header_filter, response, body_filter, log

Usage

kong.log.inspect.on()

Back to top

kong.log.inspect.off()

Disables inspect logs for this logging facility. All calls to kong.log.inspect() will be nopped.

Phases

  • init_worker, certificate, rewrite, access, header_filter, response, body_filter, log

Usage

kong.log.inspect.off()

Back to top

kong.log.set_serialize_value(key, value, options)

Sets a value to be used on the serialize custom table

Logging plugins use the output of kong.log.serialize() as a base for their logs.

This function allows customizing such output.

It can be used to replace existing values on the output. It can be used to delete existing values by passing nil.

Note: the type checking of the value parameter can take some time so it is deferred to the serialize() call, which happens in the log phase in most real-usage cases.

Phases

  • certificate, rewrite, access, header_filter, response, body_filter, log

Parameters

  • key (string): the name of the field.
  • value (number string boolean table): value to be set. When a table is used, its keys must be numbers, strings, booleans, and its values can be numbers, strings or other tables like itself, recursively.
  • options (table): can contain two entries: options.mode can be set (the default, always sets), add (only add if entry does not already exist) and replace (only change value if it already exists).

Returns

  • table the request information table

Usage

-- Adds a new value to the serialized table
kong.log.set_serialize_value("my_new_value", 1)
assert(kong.log.serialize().my_new_value == 1)

-- Value can be a table
kong.log.set_serialize_value("my", { new = { value = 2 } })
assert(kong.log.serialize().my.new.value == 2)

-- It is possible to change an existing serialized value
kong.log.set_serialize_value("my_new_value", 3)
assert(kong.log.serialize().my_new_value == 3)

-- Unset an existing value by setting it to nil
kong.log.set_serialize_value("my_new_value", nil)
assert(kong.log.serialize().my_new_value == nil)

-- Dots in the key are interpreted as table accesses
kong.log.set_serialize_value("my.new.value", 4)
assert(kong.log.serialize().my.new_value == 4)

Back to top

kong.log.serialize()

Generates a table that contains information that are helpful for logging.

This method can currently be used in the http subsystem.

The following fields are included in the returned table:

  • client_ip - client IP address in textual format.
  • latencies - request/proxy latencies.
  • request.headers - request headers.
  • request.method - request method.
  • request.querystring - request query strings.
  • request.size - size of request.
  • request.url and request.uri - URL and URI of request.
  • response.headers - response headers.
  • response.size - size of response.
  • response.status - response HTTP status code.
  • route - route object matched.
  • service - service object used.
  • started_at - timestamp this request came in, in milliseconds.
  • tries - Upstream information; this is an array and if any balancer retries occurred, will contain more than one entry.
  • upstream_uri - request URI sent to Upstream.

The following fields are only present in an authenticated request (with consumer):

  • authenticated_entity - credential used for authentication.
  • consumer - consumer entity accessing the resource.

The following fields are only present in a TLS/HTTPS request:

  • request.tls.version - TLS/SSL version used by the connection.
  • request.tls.cipher - TLS/SSL cipher used by the connection.
  • request.tls.client_verify - mTLS validation result. Contents are the same as described in $ssl_client_verify.

Warning: This function may return sensitive data (e.g., API keys). Consider filtering before writing it to unsecured locations.

All fields in the returned table may be altered via kong.log.set_serialize_value

The following http authentication headers are redacted by default, if they appear in the request:

  • request.headers.authorization
  • request.headers.proxy-authorization

To see what content is present in your setup, enable any of the logging plugins (e.g., file-log) and the output written to the log file is the table returned by this function JSON-encoded.

Phases

  • log

Returns

  • table the request information table

Usage

kong.log.serialize()

Back to top

Thank you for your feedback.
Was this page useful?
  • Kong
    THE CLOUD CONNECTIVITY COMPANY

    Kong powers reliable digital connections across APIs, hybrid and multi-cloud environments.

    • Company
    • Customers
    • Events
    • Investors
    • Careers Hiring!
    • Partners
    • Press
    • Contact
  • Products
    • Kong Konnect
    • Kong Gateway
    • Kong Mesh
    • Get Started
    • Pricing
  • Resources
    • eBooks
    • Webinars
    • Briefs
    • Blog
    • API Gateway
    • Microservices
  • Open Source
    • Install Kong Gateway
    • Kong Community
    • Kubernetes Ingress
    • Kuma
    • Insomnia
  • Solutions
    • Decentralize
    • Secure & Govern
    • Create a Dev Platform
    • API Gateway
    • Kubernetes
    • Service Mesh
Star
  • Terms•Privacy
© Kong Inc. 2022