File size: 4,317 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | package loganalyzer
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"sync"
"time"
)
type Log struct {
ID string `json:"id"`
Message string `json:"message"`
Level string `json:"level"`
Timestamp string `json:"timestamp"`
Tag string `json:"tag"`
}
type Repository interface {
Save(log Log) error
Get(id string) (Log, bool)
}
func GenerateTag(log Log) string {
text := strings.ToLower(log.Level + " " + log.Message)
switch {
case strings.Contains(text, "error"):
return "error"
case strings.Contains(text, "warn"):
return "warn"
case strings.Contains(text, "login"):
return "auth"
default:
return strings.ToLower(log.Level)
}
}
type memoryRepository struct {
mu sync.RWMutex
data map[string]Log
}
func NewMemoryRepository() Repository { return &memoryRepository{data: map[string]Log{}} }
func (r *memoryRepository) Save(log Log) error {
r.mu.Lock()
defer r.mu.Unlock()
r.data[log.ID] = log
return nil
}
func (r *memoryRepository) Get(id string) (Log, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
log, ok := r.data[id]
return log, ok
}
type fileRepository struct {
mu sync.Mutex
path string
mem Repository
}
func NewFileRepository(path string) Repository {
r := &fileRepository{path: path, mem: NewMemoryRepository()}
file, err := os.Open(path)
if err == nil {
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Buffer(make([]byte, 4096), 2*1024*1024)
for scanner.Scan() {
var item Log
if json.Unmarshal(scanner.Bytes(), &item) == nil {
_ = r.mem.Save(item)
}
}
}
return r
}
func (r *fileRepository) Save(log Log) error {
r.mu.Lock()
defer r.mu.Unlock()
file, err := os.OpenFile(r.path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return err
}
defer file.Close()
raw, err := json.Marshal(log)
if err != nil {
return err
}
_, err = file.Write(append(raw, '\n'))
if err != nil {
return err
}
return r.mem.Save(log)
}
func (r *fileRepository) Get(id string) (Log, bool) { return r.mem.Get(id) }
func NewRepositoryFromConfig(kind string, path string) Repository {
if strings.ToLower(kind) == "file" {
return NewFileRepository(path)
}
return NewMemoryRepository()
}
type Service struct{ Repo Repository }
var ErrInvalidLog = errors.New("invalid log")
func NewService(repo Repository) *Service { return &Service{Repo: repo} }
func (s *Service) Process(log Log) (Log, error) {
if strings.TrimSpace(log.ID) == "" || strings.TrimSpace(log.Message) == "" || strings.TrimSpace(log.Level) == "" || strings.TrimSpace(log.Timestamp) == "" {
return Log{}, fmt.Errorf("%w: id, message, level and timestamp are required", ErrInvalidLog)
}
if _, err := time.Parse(time.RFC3339, log.Timestamp); err != nil {
return Log{}, fmt.Errorf("%w: timestamp must be RFC3339", ErrInvalidLog)
}
if log.Tag == "" {
log.Tag = GenerateTag(log)
}
if err := s.Repo.Save(log); err != nil {
return Log{}, err
}
return log, nil
}
func NewHandler(repo Repository) http.Handler {
svc := NewService(repo)
mux := http.NewServeMux()
mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var log Log
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&log); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if decoder.Decode(new(any)) != io.EOF {
http.Error(w, "request must contain one JSON log", http.StatusBadRequest)
return
}
saved, err := svc.Process(log)
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, ErrInvalidLog) {
code = http.StatusBadRequest
}
http.Error(w, err.Error(), code)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(saved)
})
mux.HandleFunc("/log/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
id := strings.TrimPrefix(r.URL.Path, "/log/")
log, ok := repo.Get(id)
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(log)
})
return mux
}
|