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: 如果可能,打开文件时先将文件内容清空

相关推荐
小信丶13 小时前
@EnableMethodCache 注解详解:原理、应用场景与示例代码
java·spring boot·后端·spring
toooooop813 小时前
php BC MATH扩展函数巧妙进行财务金额四舍五入
开发语言·php
运维行者_13 小时前
用Applications Manager监控HAProxy:保障负载均衡高效稳定
运维·开发语言·前端·数据库·tcp/ip·负载均衡·服务器监控
wy31362282113 小时前
C#——报错:System.Net.Sockets.SocketException (10049): 在其上下文中,该请求的地址无效。
开发语言·c#·.net
遨游xyz13 小时前
策略模式笔记
开发语言·word·bash
小二·13 小时前
Go 语言系统编程与云原生开发实战(第8篇)消息队列实战:Kafka 事件驱动 × CQRS 架构 × 最终一致性(生产级落地)
云原生·golang·kafka
qq_2975746721 小时前
【实战教程】SpringBoot 集成阿里云短信服务实现验证码发送
spring boot·后端·阿里云
睡美人的小仙女12721 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
rayufo21 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk21 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea