---
title: "Referencing earlier messages of the context"
url: "https://axoflow.com/docs/axosyslog-core/4.28/chapter-correlating-log-messages/grouping-by-parser/referencing-previous-messages-grouping-by/"
last_modified: "2023-06-27T21:08:08+02:00"
---

> For the complete documentation index, see [llms.txt](https://axoflow.com/docs/axosyslog-core/4.28/llms.txt).

# Referencing earlier messages of the context

When creating the aggregated message, or in the various parameters of the `grouping-by()` parser, you can also refer to fields and values of earlier messages of the context by adding the `@<distance-of-referenced-message-from-the-current>` suffix to the macro. For example, if there are three log messages in a context, the `${HOST}@1` expression refers to the host field of the current (third) message in the context, the `${HOST}@2` expression refers to the host field of the previous (second) message in the context, `${PID}@3` to the PID of the first message, and so on. For example, the following message can be created from SSH login/logout messages: `An SSH session for ${SSH_USERNAME}@1 from ${SSH_CLIENT_ADDRESS}@2 closed. Session lasted from ${DATE}@2 to ${DATE}`.

> **Warning:**
> When referencing an earlier message of the context, always enclose the field name between braces, for example, `${PID}@3`. The reference will not work if you omit the braces.

> **Note:**
> To use a literal `@` character in a template, use `@@`.

## Example: Referencing values from an earlier message

The following action can be used to log the length of an SSH session (the time difference between a login and a logout message in the context):

```shell
   aggregate(
        value('value name="MESSAGE" An SSH session for ${SSH_USERNAME}@1 from ${SSH_CLIENT_ADDRESS}@2 closed. Session lasted from ${DATE}@2 to ${DATE}')
    )
```

If you do not know in which message of the context contains the information you need, you can use the `grep` template function. For details, see [grep](https://axoflow.com/docs/axosyslog-core/4.28/chapter-manipulating-messages/customizing-message-format/reference-template-functions/index.md).

### Example: Using the grep template function

The following example selects the message of the context that has a `username` name-value pair with the `root` value, and returns the value of the `auth_method` name-value pair.

```shell
   $(grep ("${username}" == "root") ${auth_method})
```

To perform calculations on fields that have numerical values, see [Numerical operations](https://axoflow.com/docs/axosyslog-core/4.28/chapter-manipulating-messages/customizing-message-format/reference-template-functions/index.md).

Last modified June 27, 2023: [Update paths to follow-up moving the files (6585a5b1)](https://github.com/axoflow/axosyslog-core-docs/commit/6585a5b156244e39bb831bf4e8289529f30dea0f)
