优化 MongoDB 命令监控日志:安全处理集合字段并标准化日志输出
This commit is contained in:
@@ -53,11 +53,18 @@ func commandMonitor() *event.CommandMonitor {
|
||||
return &event.CommandMonitor{
|
||||
// 命令执行前触发
|
||||
Started: func(ctx context.Context, evt *event.CommandStartedEvent) {
|
||||
// 执行前的处理逻辑示例:记录开始时间、打印执行的命令
|
||||
// 1. 安全获取集合名:先判断字段是否存在,避免空值调用
|
||||
collectionName := "无" // 默认值
|
||||
collectionVal := evt.Command.Lookup("collection")
|
||||
if !g.IsEmpty(collectionVal) { // 先检查是否为nil
|
||||
collectionName = collectionVal.StringValue()
|
||||
}
|
||||
|
||||
// 2. 打印标准化日志(避免字段缺失导致的格式错乱)
|
||||
fmt.Printf("[%s] 开始执行命令 | 数据库: %s | 集合: %s | 命令: %+v\n",
|
||||
time.Now().Format("2006-01-02 15:04:05"),
|
||||
evt.DatabaseName,
|
||||
//evt.Command.Lookup("collection").StringValue(), // 获取集合名
|
||||
collectionName,
|
||||
evt.Command,
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user