If you wish to view the script's logging documentation, you can click on this link: [Logging Documentation](https://github.com/openimsdk/open-im-server/blob/main/docs/contrib/bash-log.md).
Below is the documentation for logging and error handling in the OpenIM Go project.
To create a standard set of documentation that is quick to read and easy to understand, we will highlight key information about the `Logger` interface and the `CodeError` interface. This includes the purpose of each interface, key methods, and their use cases. This will help developers quickly grasp how to effectively use logging and error handling within the project.
## Logging (`Logger` Interface)
### Purpose
The `Logger` interface aims to provide the OpenIM project with a unified and flexible logging mechanism, supporting structured logging formats for efficient log management and analysis.
### Key Methods
- **Debug, Info, Warn, Error**
Log messages of different levels to suit various logging needs and scenarios. These methods accept a context (`context.Context`), a message (`string`), and key-value pairs (`...interface{}`), allowing the log to carry rich context information.
- **WithValues**
Append key-value pair information to log messages, returning a new `Logger` instance. This helps in adding consistent context information.
- **WithName**
Set the name of the logger, which helps in identifying the source of the logs.
- **WithCallDepth**
Adjust the call stack depth to accurately identify the source of the log message.
### Use Cases
- Developers should choose the appropriate logging level (such as `Debug`, `Info`, `Warn`, `Error`) based on the importance of the information when logging.
- Use `WithValues` and `WithName` to add richer context information to logs, facilitating subsequent tracking and analysis.
## Error Handling (`CodeError` Interface)
### Purpose
The `CodeError` interface is designed to provide a unified mechanism for error handling and wrapping, making error information more detailed and manageable.
### Key Methods
- **Code**
Return the error code to distinguish between different types of errors.
- **Msg**
Return the error message description to display to the user.
- **Detail**
Return detailed information about the error for further debugging by developers.
- **WithDetail**
Add detailed information to the error, returning a new `CodeError` instance.
- **Is**
Determine whether the current error matches a specified error, supporting a flexible error comparison mechanism.
- **Wrap**
Wrap another error with additional message description, facilitating the tracing of the error's cause.
### Use Cases
- When defining errors with specific codes and messages, use error types that implement the `CodeError` interface.
- Use `WithDetail` to add additional context information to errors for more accurate problem localization.
- Use the `Is` method to judge the type of error for conditional branching.
- Use the `Wrap` method to wrap underlying errors while adding more contextual descriptions.
In the OpenIM project, we use the unified logging package `github.com/openimsdk/tools/log` for logging to achieve efficient log management and analysis. This logging package supports structured logging formats, making it easier for developers to handle log information.
It is crucial to print entry parameters and key process information at program startup. This helps understand the startup state and configuration of the program.
**Code Example**:
```go
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Program startup, version: 1.0.0")
fmt.Printf("Connecting to database: %s\n", os.Getenv("DATABASE_URL"))
}
```
2.**Use `tools/log` and `fmt` for logging**
Logging should be done using a specialized logging library for unified management and formatted log output.
**Code Example**: Logging an info level message with `tools/log`.
6.**Handling logs for API RPC calls and non-RPC applications**
For API RPC calls using gRPC, logs at the information level are printed by middleware on the gRPC server side, reducing the need to manually log in each RPC method. For non-RPC applications, it's recommended to manually log key execution paths to track the application's execution flow.
**gRPC Server-Side Logging Middleware:**
In gRPC, `UnaryInterceptor` and `StreamInterceptor` can intercept Unary and Stream type RPC calls, respectively. Here's an example of how to implement a simple Unary RPC logging middleware:
```go
package main
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"log"
"time"
)
// unaryServerInterceptor returns a new unary server interceptor that logs each request.
For non-RPC applications, the key is to log at appropriate places in the code to maintain an execution trace. Here's a simple example showing how to log when handling a task:
In both scenarios, appropriate logging can help developers and operators monitor the health of the system, trace the source of issues, and quickly locate and resolve problems. For gRPC logging, using middleware can effectively centralize log management and control. For non-RPC applications, ensuring logs are placed at critical execution points can help understand the program's operational flow and state changes.
### When to Wrap Errors?
1.**Wrap errors generated within the function**
When an error occurs within a function, use `errs.Wrap` to add context information to the original error.
-`msg string`: The message text to append to the error.
-`kv ...any`: A variable number of parameters used to pass key-value pairs. `any` was introduced in Go 1.18 and is equivalent to `interface{}`, meaning any type.
2.**Logic**:
- If there are no key-value pairs (`kv` is empty):
- If `msg` is also empty, use `errors.WithStack(err)` to return the original error with the call stack appended.
- If `msg` is not empty, use `errors.WithMessage(err, msg)` to append the message text to the original error.
- If there are key-value pairs, the function constructs a string containing the message text and all key-value pairs. The key-value pairs are added in the format `"key=value"`, separated by commas. If a message text is provided, it is added first, followed by a space.
3.**Key-Value Pair Formatting**:
- A loop iterates over all the key-value pairs, processing one pair at a time.
- The `toString` function (although not provided in the code, we can assume it converts any type to a string) is used to convert both keys and values to strings, and they are added to a `bytes.Buffer` in the format `"key=value"`.
4.**Result**:
- Use `errors.WithMessage(err, buf.String())` to append the constructed message text to the original error, and return this new error object.
Next, let's demonstrate several ways to use the `WrapMsg` function:
**Example 1: No Additional Information**
```go
// "github.com/openimsdk/tools/errs"
err := errors.New("original error")
wrappedErr := errs.WrapMsg(err, "")
// wrappedErr will contain the original error and its call stack
// wrappedErr will contain the original error, call stack, and "user=john_doe, action=login"
```
> [!TIP] WThese examples demonstrate how the `errs.WrapMsg` function can flexibly handle error messages and context data, helping developers to more effectively track and debug their programs.
### Example 5: Dynamic Key-Value Pairs from Context
Suppose we have some runtime context variables, such as a user ID and the type of operation being performed, and we want to include these variables in the error message. This can help with later debugging and identifying the specific environment of the issue.
// wrappedErr will contain the original error, call stack, and "operation failed user=user123, action=update profile, code=500, url=http://example.com/updateProfile"
```
> [!TIP]In this example, the `WrapMsg` function accepts not just a static error message and additional information, but also dynamic key-value pairs generated from the code's execution context, such as the user ID, operation type, error code, and the URL of the request. Including this contextual information in the error message makes it easier for developers to understand and resolve the issue.