---
title: "定时任务-日志管理"
url: "https://goframe.org/docs/components/os-gcron-logging"
markdown_url: "https://goframe.org/docs/components/os-gcron-logging.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "组件列表"
category: "组件列表 / 系统相关 / 定时任务-gcron"
published: "2024-10-21"
updated: "2024-11-11"
description: "在GoFrame框架中的gcron组件中进行日志管理。gcron支持设置日志输出文件和级别，默认记录错误级别日志。通过GoFrame框架的日志组件，用户可以复用日志的所有特性。文章中提供了Go代码示例，展示了如何设置和使用gcron的日志功能。"
keywords: ["GoFrame", "GoFrame框架", "gcron", "日志管理", "定时任务", "日志组件", "日志输出", "日志级别", "GoFrame日志", "glog"]
---

# 定时任务-日志管理

`gcron` 支持日志功能，并可设置日志输出的文件以及级别。默认情况下仅会输出 `LEVEL_WARN | LEVEL_ERRO | LEVEL_CRIT` 错误级别的日志（包括定时任务运行异常日志），运行日志以 `LEVEL_DEBUG` 的级别进行记录，因此默认不会记录。 `gcron` 组件使用了 `goframe` 框架统一的日志组件，因此可以复用日志组件的所有特性。相关方法：

```go
func SetLogger(logger glog.ILogger)
func GetLogger() glog.ILogger
```
:::tip
日志组件特性请参考 [日志组件](https://goframe.org/docs/core/glog) 章节。
:::
使用示例：

```go
package main

import (
    "context"
    "github.com/gogf/gf/v2/frame/g"
    "github.com/gogf/gf/v2/os/gcron"
    "github.com/gogf/gf/v2/os/gctx"
    "github.com/gogf/gf/v2/os/glog"
    "time"
)

func main() {
    var (
        err    error
        ctx    = gctx.New()
        logger = glog.New()
    )
    logger.SetLevel(glog.LEVEL_ALL)
    gcron.SetLogger(logger)
    _, err = gcron.Add(ctx, "* * * * * ?", func(ctx context.Context) {
        g.Log().Info(ctx, "test")
    })
    if err != nil {
        panic(err)
    }
    time.Sleep(3 * time.Second)
}
```

执行后，终端输出结果为：

![](https://goframe.org/markdown/673cee2f61375b3979a03c30934fd8d8.png)
