knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/test/logstream/README.md (about)

     1  # How to use logstream
     2  
     3  This is a guide to start using `logstream` in your e2e testing.
     4  
     5  ## Requirements
     6  
     7  1. The `SYSTEM_NAMESPACE` environment variable must be configured. Many of the
     8     knative test scripts already define this, and in some places (e.g. serving)
     9     randomize it. However, to facilitate usage outside of CI, you should consider
    10     including a package like
    11     [this](https://github.com/knative/serving/blob/main/test/defaultsystem/system.go)
    12     and linking it like
    13     [this](https://github.com/knative/serving/blob/e797247322b5aa35001152d2a2715dbc20a86cc4/test/conformance.go#L20-L23)
    14  
    15  2. Test resources must be named with
    16     [`test.ObjectNameForTest(t)`](https://github.com/knative/networking/blob/40ef99aa5db0d38730a89a1de7e5b28b8ef6eed5/vendor/knative.dev/pkg/test/helpers/name.go#L50)
    17  
    18  3. At the start of your test add: `t.Cleanup(logstream.Start(t))`
    19  
    20  4. To enable logcapture from containers across multiple namespaces configure
    21     SYSTEM_NAMESPACE to contains a csv list of namespaces
    22     (`knative-serving,knative-test ??????{}`). Specific, well known containers
    23     that do not produce key decorated logs (see detailed description below) need
    24     to be enumerated in WellKnownContainers in stream.go.
    25  
    26  With that, you will start getting logs from the processes in the system
    27  namespace interleaved into your test output via `t.Log`.
    28  
    29  ## How it works
    30  
    31  In Knative we use `zap.Logger` for all of our logging, and most of those loggers
    32  (e.g. in the context of a reconcile) have been decorated with the "key" of the
    33  resource being processed. `logstream` simply decodes these structured log
    34  messages and when the `key` matches the naming prefix that `ObjectNameForTest`
    35  uses, it includes it into the test's output.
    36  
    37  ## Integrating in Libraries.
    38  
    39  When a shared component is set up and called from reconciliation, it may have
    40  it's own logger. If that component is dealing with individual resources, it can
    41  scope individual log statements to that resource by decorating the logger with
    42  its key like so:
    43  
    44  ```
    45  logger := logger.With(zap.String(logkey.Key, resourceKey))
    46  ```
    47  
    48  Now, any log statements that the library prints through this logger will appear
    49  in the logstream!
    50  
    51  For an example of this pattern, see
    52  [the knative/networking prober library](https://github.com/knative/networking/blob/main/pkg/status/status.go).