Logging in Ethereum

The EVM currently has 5 opcodes for emitting event logs: LOG0, LOG1, LOG2, LOG3, and LOG4.

These opcodes can be used to create log records. A log record can be used to describe an event within a smart contract, like a token transfer or a change of ownership.

Each log record consists of both topics and data. Topics are 32-byte (256 bit) "words" that are used to describe what's going on in an event. Different opcodes (LOG0 ... LOG4) are needed to describe the number of topics that need to be included in the log record. For instance, LOG1 includes one topic, while LOG4 includes four topics. Therefore, the maximum number of topics that can be included in a single log record is four.

Topics in Ethereum Log Records

The first part of a log record consists of an array of topics. These topics are used to describe the event. The first topic usually consists of the signature (a keccak256 hash) of the name of the event that occurred, including the types (uint256, string, etc.) of its parameters. One exception where this signature is not included as the first topic is when emitting anonymous events.

Since topics can only hold a maximum of 32 bytes of data, things like arrays or strings cannot be used as topics reliably. Instead, it should be included as data in the log record, not as a topic. If you were trying to include a topic that's larger than 32 bytes, the topic will be hashed instead. As a result, this hash can only be reversed if you know the original input.

In conclusion, topics should only reliably be used for data that strongly narrows down search queries (like addresses). So topics can also be seen as indexed keys of the event that all map to the same value.

Data in Ethereum Log Records

The second part of a log record consists of additional data. Topics and data work best together as there are upsides and downsides to each. For example, while topics are searchable, data is not. But, including data is a lot cheaper than including topics.

Additionally, while topics are limited to 4 * 32 bytes, event data is not, which means it can include large or complicated data like arrays or strings. Therefore, the event data can be seen as the value.