Golang 写日志到文件

Go 复制代码
package main

import (
	"log"
	"os"
	"time"
)

func main() {
	printLog("auto", "报警内容AA")
}

func printLog(filename string, content string) {
	t := time.Now().Format(time.DateOnly)
	file := filename + "." + t + ".log"
    //日志名称为 xx.2024-03-07.log

	f, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		log.Panic("打开日志文件异常")
	}
	defer f.Close() // 延迟关闭文件句柄
	log.SetOutput(f)
	log.Print(content)
}

OpenFile常用的打开模式:

os.O_RDONLY: 以只读方式打开文件

os.O_WRONLY: 以只写方式打开文件

os.O_RDWR: 以读写方式打开文件

os.O_APPEND: 在文件末尾追加数据

os.O_CREATE: 如果文件不存在则创建新文件

os.O_EXCL: 与O_CREATE一起使用时,要求文件必须是新创建的,如果文件已经存在则返回错误

os.O_SYNC: 打开文件用于同步I/O

os.O_TRUNC: 如果可能,打开文件时先将文件内容清空

相关推荐
2301_765703149 分钟前
C++中的协程编程
开发语言·c++·算法
m0_7487080510 分钟前
实时数据压缩库
开发语言·c++·算法
lly2024061 小时前
jQuery Mobile 表格
开发语言
惊讶的猫1 小时前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
m0_748233172 小时前
30秒掌握C++核心精髓
开发语言·c++
Fleshy数模2 小时前
从数据获取到突破限制:Python爬虫进阶实战全攻略
java·开发语言
Duang007_2 小时前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
froginwe112 小时前
Redis 管道技术
开发语言
有来技术2 小时前
Spring Boot 4 + Vue3 企业级多租户 SaaS:从共享 Schema 架构到商业化套餐设计
java·vue.js·spring boot·后端
u0109272712 小时前
C++中的RAII技术深入
开发语言·c++·算法