SoFunction
Updated on 2025-03-03

Detailed explanation of the wonderful uses of XOR combination configuration in Go

You must have seen this usage in log:

( |  | )

I haven't seen it before, reflect on myself (escape

In GologIn the package, use "bit operation phase or" (|) to configure logsflag, is to allow us to flexibly combine multiple log information output options. , such as whether to display date, time, microseconds, file name, line number, etc.

Next, we will explain the benefits and principles of this method in detail.

1. What is a flag in a log package

existlogIn the package,flagSome options are used to control the log output format.

EachflagThey are all binary bit masks. Through different mask combinations, the content of the log can be controlled.

TheseflagThe options are defined as follows:

const (
    Ldate         = 1 << iota     // Date: 2009/01/23    Ltime                         // Time: 01:23:23    Lmicroseconds                 // Microsecond time: 01:23:23.123123 (Ltime is required)    Llongfile                     // Complete file name and line number: /a/b/c/:23    Lshortfile                    // File name and line number::23 (will overwrite Llongfile)    LUTC                          // Use UTC time instead of local time    Lmsgprefix                    // Move the "prefix" from the beginning of the line to the front of the message    LstdFlags     = Ldate | Ltime // default value)

These constants areDisplacement operation 1 << iotaDefined, guaranteed eachflagOnly one is occupied and it is unique.

In this way, we can use bitwise or operation|To combine multiple options.

The corresponding values ​​are as follows:

const (
	Ldate=1 &lt;&lt; iota// iota = 0, the value is 1 << 0 = 1, binary: 00000001, equivalent to the power of 2	Ltime          // iota = 1, the value is 1 << 1 = 2, binary: 00000010, equivalent to the power of 2	Lmicroseconds  // iota = 2, the value is 1 << 2 = 4, binary: 00000100, equivalent to the power of 2	Llongfile      // iota = 3, the value is 1 << 3 = 8, binary: 00001000, equivalent to the power of 2 to 3	Lshortfile     // iota = 4, the value is 1 << 4 = 16, binary: 00010000, equivalent to the 4th power of 2	LUTC           // iota = 5, the value is 1 << 5 = 32, binary: 00100000, equivalent to the 5th power of 2	Lmsgprefix     // iota = 6, the value is 1 << 6 = 64, binary: 01000000, equivalent to the power of 2 to 6)

2. Why use bitwise or (|) to combine flags

bitwise or (|) The benefit isAny combination of options can be done. Because everyflagConstants represent a unique binary bit, so they can be combined together by bitwise or addition without conflict. For example:

  • LtimeThe value is1 << 1,Right now0b0010
  • LlongfileThe value is1 << 3,Right now0b1000

When we use(Ltime | Llongfile)When, it is equivalent to0b0010 | 0b1000Combined0b1010, that is, the time and file name short format display is enabled at the same time.

Through this bit operation method, various types offlagoption without having to redefine a new constant for each combination.

3. Advantages of using bitwise or combination flags

  • High flexibility: You can freely select a combination of multiple options to meet different needs without having to specify each one by oneflag
  • Strong readability: Bitwise or combination expressions are simple and clear, showing clearly what functions are enabled.
  • Efficiency: The bit operation itself is efficient and has small calculation amount, andflagConstants are designed as binary masks for quick combination and interpretation.

4. How to identify the set flag

When we pass multiple flags through bits or combinationsback,logThe package detects the combined value when outputting the log and determines the output content based on different bit settings.

Specific identification method: bitwise and (&) operation

Suppose we set the following flag combination:

( |  | )

The incoming flag combination will be an integer value.logWhen generating logs, the package will determine whether each flag exists by bitwise and operation. The specific steps are as follows:

  • examineLdate: Use bitwise and operationflags & Ldate, if the result is not 0, it meansLdateHas been set, the log will contain date information.
  • examineLtime: Similarly, byflags & Ltime, non-zeroLtimeSet, the log will contain time information.
  • examineLlongfile: Check by bitflags & Llongfile, determine whether to output the file path (full path) by determining the value.

Specifically, suppose we use | |

  • LdateThe value of00000001
  • LtimeThe value of00000010
  • LlongfileThe value of00001000

The integer value after combining these flags is00001011, it contains all the settings information.

Example: The process of code implementing flag recognition

bylogTaking the implementation principle of the package as an example, the process of flag recognition can be roughly simulated. AssumptionsflagsThe variable stores the current flag setting value, and you can determine whether each function is enabled as follows:

package main

import (
    "log"
)

func main() {
    flags :=  |  | 

    if flags&amp; != 0 {
        ("Date enabled")
    }
    if flags&amp; != 0 {
        ("Time is enabled")
    }
    if flags&amp; != 0 {
        ("Full file path enabled")
    }
}

5. Use display

Let's look at an example, assuming this code is located inLine 10 of the file:

package main

import (
    "log"
)

func main() {
    ( | )
    ("This is a log message")
}

If this code is executed at 15:04:05 on November 3, 2024, the log output might be:

15:04:05 :10: This is a log message

in,15:04:05It's time,:10is a simplified file name and line number.

6. Summary

Use bitwise or operator|To configure logsflag, which allows us to flexibly combine different display options for logs and conveniently customize the output format. This approach not only simplifies the code, but also improves the flexibility and readability of log configuration.

This is the article about the wonderful use of XOR configuration in Go. For more information about XOR content related to XOR content of the Go log package, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!