Skip to content

Commit

Permalink
feature: support makefile, cuslog 0 module design
Browse files Browse the repository at this point in the history
Signed-off-by: Xinwei Xiong(cubxxw) <3293172751nss@gmail.com>
  • Loading branch information
cubxxw committed Apr 23, 2023
1 parent 53cb7dd commit 75b9313
Show file tree
Hide file tree
Showing 23 changed files with 1,297 additions and 2 deletions.
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@
*.out

# Dependency directories (remove the comment below to include it)
# vendor/
vendor/
bin/
_output/
tools/
tmp/

# Go workspace file
go.work
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2023 Kubernetes Cub community
Copyright (c) 2023 KubeCub.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
140 changes: 140 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# Copyright 2023 KubeCub. All rights reserved.
# Use of this source code is governed by a MIT style
# license that can be found in the LICENSE file.

# ==============================================================================
# define the default goal
#
ROOT_PACKAGE=github.com/kubecub/log

SHELL := /bin/bash
DIRS=$(shell ls)
GO=go

.DEFAULT_GOAL := help

# include the common makefile
COMMON_SELF_DIR := $(dir $(lastword $(MAKEFILE_LIST)))
# ROOT_DIR: root directory of the code base
ifeq ($(origin ROOT_DIR),undefined)
ROOT_DIR := $(abspath $(shell cd $(COMMON_SELF_DIR)/. && pwd -P))
endif
# OUTPUT_DIR: The directory where the build output is stored.
ifeq ($(origin OUTPUT_DIR),undefined)
OUTPUT_DIR := $(ROOT_DIR)/bin
$(shell mkdir -p $(OUTPUT_DIR))
endif

ifeq ($(origin VERSION), undefined)
VERSION := $(shell git describe --abbrev=0 --dirty --always --tags | sed 's/-/./g')
endif

# Check if the tree is dirty. default to dirty(maybe u should commit?)
GIT_TREE_STATE:="dirty"
ifeq (, $(shell git status --porcelain 2>/dev/null))
GIT_TREE_STATE="clean"
endif
GIT_COMMIT:=$(shell git rev-parse HEAD)

IMG ?= ghcr.io/kubecub/log:latest

BUILDFILE = "./main.go"
BUILDAPP = "$(OUTPUT_DIR)/"

# Define the directory you want to copyright
CODE_DIRS := $(ROOT_DIR) #$(ROOT_DIR)/pkg $(ROOT_DIR)/core $(ROOT_DIR)/integrationtest $(ROOT_DIR)/lib $(ROOT_DIR)/mock $(ROOT_DIR)/db $(ROOT_DIR)/openapi
FINDS := find $(CODE_DIRS)

ifndef V
MAKEFLAGS += --no-print-directory
endif

# Linux command settings
FIND := find . ! -path './image/*' ! -path './vendor/*' ! -path './bin/*'
XARGS := xargs -r
LICENSE_TEMPLATE ?= $(ROOT_DIR)/scripts/boilerplate.txt

# ==============================================================================
# Targets

## all: Build all the necessary targets.
.PHONY: all
all: tidy add-copyright lint cover build

## build: Build binaries by default.
.PHONY: build
build:
@echo "$(shell go version)"
@echo "===========> Building binary $(BUILDAPP) *[Git Info]: $(VERSION)-$(GIT_COMMIT)"
@export CGO_ENABLED=0 && go build -o $(BUILDAPP) -ldflags '-s -w' $(BUILDFILE)

## build.%: Builds a binary of the specified directory.
.PHONY: build.%
build.%:
@echo "$(shell go version)"
@echo "===========> Building binary $(BUILDAPP) *[Git Info]: $(VERSION)-$(GIT_COMMIT)"
@export CGO_ENABLED=0 && GOOS=linux go build -o $(BUILDAPP)/$*/ -ldflags '-s -w' $*/example/$(BUILDFILE)
@export CGO_ENABLED=0 && GOOS=linux go build -o $(BUILDAPP)/$*/ -ldflags '-s -w' $*/example/$(BUILDFILE)


## tidy: tidy go.mod
.PHONY: tidy
tidy:
@$(GO) mod tidy

## fmt: Run go fmt against code.
.PHONY: fmt
fmt:
@$(GO) fmt ./...

## vet: Run go vet against code.
.PHONY: vet
vet:
@$(GO) vet ./...

## lint: Run go lint against code.
.PHONY: lint
lint:
@golangci-lint run -v ./...

## style: Code style -> fmt,vet,lint
.PHONY: style
style: fmt vet lint

## test: Run unit test
.PHONY: test
test:
@echo "===========> Run unit test"
@$(GO) test ./...

## cover: Run unit test with coverage.
.PHONY: cover
cover: test
@$(GO) test -cover

## copyright.verify: Validate boilerplate headers for assign files.
.PHONY: copyright-verify
copyright-verify:
@echo "===========> Validate boilerplate headers for assign files starting in the $(ROOT_DIR) directory"
@addlicense -v -check -ignore **/test/** -f $(LICENSE_TEMPLATE) $(CODE_DIRS)
@echo "===========> End of boilerplate headers check..."

## copyright-add: Add the boilerplate headers for all files.
.PHONY: copyright-add
copyright-add:
@echo "===========> Adding $(LICENSE_TEMPLATE) the boilerplate headers for all files"
@addlicense -y $(shell date +"%Y") -v -c "KubeCub." -f $(LICENSE_TEMPLATE) $(CODE_DIRS)
@echo "===========> End the copyright is added..."

## go.clean: Clean all builds.
.PHONY: clean
clean:
@echo "===========> Cleaning all builds OUTPUT_DIR($(OUTPUT_DIR))"
@-rm -vrf $(OUTPUT_DIR)
@echo "===========> End clean..."

## help: Show this help info.
.PHONY: help
help: Makefile
@printf "\n\033[1mUsage: make <TARGETS> ...\033[0m\n\n\\033[1mTargets:\\033[0m\n\n"
@sed -n 's/^##//p' $< | awk -F':' '{printf "\033[36m%-28s\033[0m %s\n", $$1, $$2}' | sed -e 's/^/ /'
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Project myproject

<!-- Write one paragraph of this project description here -->

## Features

<!-- Tell others the features of this project -->

## Getting Started

### Prerequisites

<!-- Describe packages, tools and everything we needed here -->

### Building

<!-- Describe how to build this project -->

### Running

<!-- Describe how to run this project -->

## Using

<!-- Place user documents here -->

## Contributing

<!-- Tell others how to contribute this project -->

## Community(optional)

<!-- Tell something about the community if needed -->

## Authors

<!-- Put authors here -->

## License

<!-- A link to license file -->
68 changes: 68 additions & 0 deletions cuslog/entry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright © 2023 KubeCub. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.

package cuslog

import (
"bytes"
"runtime"
"strings"
"time"
)

type Entry struct {
logger *logger
Buffer *bytes.Buffer
Map map[string]interface{}
Level Level
Time time.Time
File string
Line int
Func string
Format string
Args []interface{}
}

func entry(logger *logger) *Entry {
return &Entry{logger: logger, Buffer: new(bytes.Buffer), Map: make(map[string]interface{}, 5)}
}

func (e *Entry) write(level Level, format string, args ...interface{}) {
if e.logger.opt.level > level {
return
}
e.Time = time.Now()
e.Level = level
e.Format = format
e.Args = args
if !e.logger.opt.disableCaller {
if pc, file, line, ok := runtime.Caller(2); !ok {
e.File = "???"
e.Func = "???"
} else {
e.File, e.Line, e.Func = file, line, runtime.FuncForPC(pc).Name()
e.Func = e.Func[strings.LastIndex(e.Func, "/")+1:]
}
}
e.format()
e.writer()
e.release()
}

func (e *Entry) format() {
_ = e.logger.opt.formatter.Format(e)
}

func (e *Entry) writer() {
e.logger.mu.Lock()
_, _ = e.logger.opt.output.Write(e.Buffer.Bytes())
e.logger.mu.Unlock()
}

func (e *Entry) release() {
e.Args, e.Line, e.File, e.Format, e.Func = nil, 0, "", "", ""
e.Buffer.Reset()
e.logger.entryPool.Put(e)
}
35 changes: 35 additions & 0 deletions cuslog/example/example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright © 2023 KubeCub. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.

package main

import (
"log"
"os"

"github.com/kubecub/log/cuslog"
)

func main() {
cuslog.Info("std log")
cuslog.SetOptions(cuslog.WithLevel(cuslog.DebugLevel))
cuslog.Debug("change std log to debug level")
cuslog.SetOptions(cuslog.WithFormatter(&cuslog.JsonFormatter{IgnoreBasicFields: false}))
cuslog.Debug("log in json format")
cuslog.Info("another log in json format")

// 输出到文件
fd, err := os.OpenFile("test.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalln("create file test.log failed")
}
defer fd.Close()

l := cuslog.New(cuslog.WithLevel(cuslog.InfoLevel),
cuslog.WithOutput(fd),
cuslog.WithFormatter(&cuslog.JsonFormatter{IgnoreBasicFields: false}),
)
l.Info("custom log with json formatter")
}
32 changes: 32 additions & 0 deletions cuslog/example/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright © 2023 KubeCub. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.

package main

import (
"log"
"os"

"github.com/kubecub/log/cuslog"
)

func main() {
cuslog.Info("std log")
cuslog.SetOptions(cuslog.WithLevel(cuslog.DebugLevel))
cuslog.Debug("change std log to debug level")

// 输出到文件
fd, err := os.OpenFile("test.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalln("create file test.log failed")
}
defer fd.Close()

l := cuslog.New(cuslog.WithLevel(cuslog.InfoLevel),
cuslog.WithOutput(fd),
cuslog.WithFormatter(&cuslog.JsonFormatter{IgnoreBasicFields: false}),
)
l.Info("custom log with json formatter")
}
11 changes: 11 additions & 0 deletions cuslog/example/test.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{"level":"INFO","time":"2020-11-30T21:49:16+08:00","message":"custom log with json formatter"}
{"level":"INFO","time":"2020-11-30T21:49:27+08:00","file":"/home/colin/workspace/golang/src/github.com/marmotedu/gopractise-demo/log/cuslog/example/main.go:27","func":"main.main","message":"custom log with json formatter"}
{"level":"INFO","time":"2020-11-30T21:49:34+08:00","file":"/home/colin/workspace/golang/src/github.com/marmotedu/gopractise-demo/log/cuslog/example/main.go:26","func":"main.main","message":"custom log with json formatter"}
{"level":"INFO","time":"2020-11-30T21:49:35+08:00","file":"/home/colin/workspace/golang/src/github.com/marmotedu/gopractise-demo/log/cuslog/example/main.go:26","func":"main.main","message":"custom log with json formatter"}
{"time":"2020-12-01T06:57:52+08:00","file":"/home/colin/workspace/golang/src/github.com/marmotedu/gopractise-demo/log/cuslog/example/main.go:26","func":"main.main","message":"custom log with json formatter","level":"INFO"}
{"file":"/home/colin/workspace/golang/src/github.com/marmotedu/gopractise-demo/log/cuslog/example/main2.go:28","func":"main.main","message":"custom log with json formatter","level":"INFO","time":"2020-12-02T01:13:28+08:00"}
{"level":"INFO","time":"2020-12-02T01:15:26+08:00","file":"/home/colin/workspace/golang/src/github.com/marmotedu/gopractise-demo/log/cuslog/example/example.go:28","func":"main.main","message":"custom log with json formatter"}
{"level":"INFO","time":"2020-12-02T01:16:18+08:00","file":"/home/colin/workspace/golang/src/github.com/marmotedu/gopractise-demo/log/cuslog/example/example.go:29","func":"main.main","message":"custom log with json formatter"}
{"time":"2020-12-04T09:10:54+08:00","file":"/home/colin/workspace/golang/src/github.com/marmotedu/gopractise-demo/log/cuslog/example/main.go:26","func":"main.main","message":"custom log with json formatter","level":"INFO"}
{"func":"main.main","message":"custom log with json formatter","level":"INFO","time":"2020-12-04T09:10:56+08:00","file":"/home/colin/workspace/golang/src/github.com/marmotedu/gopractise-demo/log/cuslog/example/example.go:29"}{"func":"main.main","message":"custom log with json formatter","level":"INFO","time":"2023-04-22T21:25:22+08:00","file":"/root/workspaces/log/cuslog/example/example.go:29"}
{"level":"INFO","time":"2023-04-22T21:25:24+08:00","file":"/root/workspaces/log/cuslog/example/main.go:26","func":"main.main","message":"custom log with json formatter"}
12 changes: 12 additions & 0 deletions cuslog/formatter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright © 2023 KubeCub. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.

package cuslog

type Formatter interface {
// Maybe in async goroutine
// Please write the result to buffer
Format(entry *Entry) error
}
Loading

0 comments on commit 75b9313

Please sign in to comment.