go语言实现一个简易日志系统

代码示例评论阅读9分21秒

要求:

1. 系统应包含日志记录、存储、查询和删除等功能。文章源自Golang编程指南-https://www.va26.com/work/140.html

2. 日志记录应支持记录不同类型的数据,如:时间戳、错误代码、错误信息等。文章源自Golang编程指南-https://www.va26.com/work/140.html

3. 存储部分应支持对日志进行持久化存储,以便后续可以读取和查看。文章源自Golang编程指南-https://www.va26.com/work/140.html

4. 查询和删除功能应支持对日志的查询和删除操作,确保数据的完整性和安全性。文章源自Golang编程指南-https://www.va26.com/work/140.html

5. 系统应具备良好的可扩展性和可维护性,方便后续的功能扩展和错误修复。文章源自Golang编程指南-https://www.va26.com/work/140.html

文章源自Golang编程指南-https://www.va26.com/work/140.html

下面是一个简单的Go语言日志系统的实现示例,它满足了上述要求:文章源自Golang编程指南-https://www.va26.com/work/140.html

package main  
  
import (  
	"encoding/json"  
	"fmt"  
	"io/ioutil"  
	"os"  
	"time"  
)  
  
// LogEntry represents a single log entry  
type LogEntry struct {  
	Timestamp    time.Time `json:"timestamp"`  
	ErrorCode    int       `json:"errorCode,omitempty"`  
	ErrorMessage string    `json:"errorMessage"`  
	// Additional fields can be added here  
}  
  
// LogManager manages logging, storage, retrieval, and deletion of log entries  
type LogManager struct {  
	logFile *os.File  
}  
  
// NewLogManager creates a new LogManager instance  
func NewLogManager(logFile string) (*LogManager, error) {  
	file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)  
	if err != nil {  
		return nil, err  
	}  
	return &LogManager{logFile: file}, nil  
}  
  
// Log records a new log entry  
func (lm *LogManager) Log(errorCode int, errorMessage string) error {  
	entry := LogEntry{  
		Timestamp:    time.Now(),  
		ErrorCode:    errorCode,  
		ErrorMessage: errorMessage,  
	}  
	entryJSON, err := json.Marshal(entry)  
	if err != nil {  
		return err  
	}  
	_, err = lm.logFile.Write(entryJSON)  
	if err != nil {  
		return err  
	}  
	_, err = lm.logFile.WriteString("\n")  
	return err  
}  
  
// Close closes the log file  
func (lm *LogManager) Close() error {  
	return lm.logFile.Close()  
}  
  
// ReadLogs reads and returns all log entries from the log file  
func ReadLogs(logFile string) ([]LogEntry, error) {  
	data, err := ioutil.ReadFile(logFile)  
	if err != nil {  
		return nil, err  
	}  
	var logs []LogEntry  
	err = json.Unmarshal(data, &logs)  
	if err != nil {  
		// If the entire file content is not a valid JSON array,  
		// we try to parse each line separately  
		lines := string(data[:])  
		entries := []LogEntry{}  
		for _, line := range SplitLines(lines) {  
			var entry LogEntry  
			if err := json.Unmarshal([]byte(line), &entry); err != nil {  
				fmt.Printf("Error parsing line: %s\n", err)  
				continue  
			}  
			entries = append(entries, entry)  
		}  
		return entries, nil  
	}  
	return logs, nil  
}  
  
// DeleteLogs clears the log file  
func DeleteLogs(logFile string) error {  
	return os.Remove(logFile)  
}  
  
// Helper function to split lines  
func SplitLines(s string) []string {  
	lines := []string{}  
	start := 0  
	for i, r := range s {  
		if r == '\n' {  
			lines = append(lines, s[start:i])  
			start = i + 1  
		}  
	}  
	if start < len(s) {  
		lines = append(lines, s[start:])  
	}  
	return lines  
}  
  
func main() {  
	logFile := "log.txt"  
  
	// Initialize LogManager  
	lm, err := NewLogManager(logFile)  
	if err != nil {  
		panic(err)  
	}  
	defer lm.Close()  
  
	// Log some entries  
	lm.Log(404, "Resource not found")  
	lm.Log(500, "Internal server error")  
  
	// Read logs  
	entries, err := ReadLogs(logFile)  
	if err != nil {  
		panic(err)  
	}  
	for _, entry := range entries {  
		fmt.Printf("Timestamp: %s, ErrorCode: %d, ErrorMessage: %s\n", entry.Timestamp, entry.ErrorCode, entry.ErrorMessage)  
	}  
  
	// Delete logs  
	err = DeleteLogs(logFile)  
	if err != nil {  
		panic(err)  
	}  
}

这个示例包含了一个LogManager结构体,它负责管理日志文件的写入。LogEntry结构体表示日志条目,包含时间戳、错误代码和错误信息。ReadLogs函数从日志文件中读取并返回所有的日志条目,DeleteLogs函数则用于删除日志文件。文章源自Golang编程指南-https://www.va26.com/work/140.html

注意:这个示例是一个基本的实现,它没有处理并发写入,也没有实现复杂的查询功能。在实际应用中,您可能需要添加锁来确保并发安全,以及实现更复杂的查询和过滤功能。文章源自Golang编程指南-https://www.va26.com/work/140.html

此外,对于生产环境的日志系统,您可能需要考虑使用像Logstash、ELK Stack(Elasticsearch、Logstash、Kibana)或其他现成的日志解决方案,这些解决方案提供了强大的日志收集、存储、分析和可视化功能。文章源自Golang编程指南-https://www.va26.com/work/140.html

 

 
  • 本文由golang编程指南作者原创,请勿恶意转载!
  • 转载请务必保留本文链接:https://www.va26.com/work/140.html
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证