Skip to content

Commit 34b516d

Browse files
committed
add logger message format
1 parent df570b9 commit 34b516d

File tree

6 files changed

+158
-113
lines changed

6 files changed

+158
-113
lines changed

README.md

Lines changed: 88 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,51 @@ A simple but powerful golang log Toolkit
1818
go get github.com/phachon/go-logger
1919
go get ./...
2020
```
21+
2122
# Requirement
2223
go 1.8
2324

2425
# Support outputs
25-
- console //write console
26-
- file //write file
26+
- console // write console
27+
- file // write file
2728
- api // http request url
2829
- ...
2930

3031

31-
# Use
32+
# Quick Used
3233

33-
- ### example
34+
- sync
35+
36+
```
37+
import (
38+
"github.com/phachon/go-logger"
39+
)
40+
func main() {
41+
logger := go_logger.NewLogger()
42+
43+
logger.Info("this is a info log!")
44+
logger.Errorf("this is a error %s log!", "format")
45+
}
46+
```
47+
48+
- async
49+
50+
```
51+
import (
52+
"github.com/phachon/go-logger"
53+
)
54+
func main() {
55+
logger := go_logger.NewLogger()
56+
logger.SetAsync()
57+
58+
logger.Info("this is a info log!")
59+
logger.Errorf("this is a error %s log!", "format")
60+
61+
logger.Flush()
62+
}
63+
```
64+
65+
- Multiple output
3466

3567
```
3668
import (
@@ -39,106 +71,86 @@ import (
3971
func main() {
4072
logger := go_logger.NewLogger()
4173
42-
// The default has been added to the output of console, and the default does not display the color. If you need to modify it, delete the console first
4374
logger.Detach("console")
4475
45-
// config console
76+
// console adapter config
4677
consoleConfig := &go_logger.ConsoleConfig{
47-
Color: true, // text show color
48-
JsonFormat: true, // json format
49-
ShowFileLine: true, // when JsonFormat is false, console show file line, default false
78+
Color: true, // Does the text display the color
79+
JsonFormat: true, // Whether or not formatted into a JSON string
80+
Format: "" // JsonFormat is false, logger message output to console format string
5081
}
51-
// attach console to outputs
82+
// add output to the console
5283
logger.Attach("console", go_logger.LOGGER_LEVEL_DEBUG, consoleConfig)
5384
54-
// config file
55-
fileConfig := &go_logger.FileConfig{
56-
Filename : "./test.log", // The file name of the log output does not exist automatically.
57-
// If you want to output different levels of logs to a file individually, configure the LevelFileName parameter.
85+
// file adapter config
86+
fileConfig := &go_logger.FileConfig {
87+
Filename : "./test.log", // The file name of the logger output, does not exist automatically
88+
// If you want to separate separate logs into files, configure LevelFileName parameters.
5889
LevelFileName : map[int]string {
5990
logger.LoggerLevel("error"): "./error.log", // The error level log is written to the error.log file.
60-
logger.LoggerLevel("info"): "./info.log", // The info level log is written to the info.log file.
91+
logger.LoggerLevel("info"): "./info.log", // The info level log is written to the info.log file.
6192
logger.LoggerLevel("debug"): "./debug.log", // The debug level log is written to the debug.log file.
6293
},
63-
MaxSize : 1024 * 1024, // max file size(kb)
64-
MaxLine : 100000, // max file line
65-
DateSlice : "d", // slice file by date, support "y", "m", "d", "h", default "" not slice
66-
JsonFormat: true, // json format
94+
MaxSize : 1024 * 1024, // File maximum (KB), default 0 is not limited
95+
MaxLine : 100000, // The maximum number of lines in the file, the default 0 is not limited
96+
DateSlice : "d", // Cut the document by date, support "Y" (year), "m" (month), "d" (day), "H" (hour), default "no".
97+
JsonFormat: true, // Whether the file data is written to JSON formatting
98+
Format: "" // JsonFormat is false, logger message written to file format string
6799
}
100+
// add output to the file
68101
logger.Attach("file", go_logger.LOGGER_LEVEL_DEBUG, fileConfig)
69102
70-
// Set to asynchronous, default is synchronous output
71-
logger.SetAsync()
72103
73-
logger.Emergency("this is a emergency log!")
74-
logger.Alert("this is a alert log!")
75-
logger.Critical("this is a critical log!")
76-
logger.Error("this is a error log!")
77-
logger.Warning("this is a warning log!")
78-
logger.Notice("this is a notice log!")
79104
logger.Info("this is a info log!")
80-
logger.Debug("this is a debug log!")
81-
82-
logger.Emergencyf("this is a emergency %d log!", 10)
83-
logger.Alertf("this is a alert %s log!", "format")
84-
logger.Criticalf("this is a critical %s log!", "format")
85105
logger.Errorf("this is a error %s log!", "format")
86-
logger.Warningf("this is a warning %s log!", "format")
87-
logger.Noticef("this is a notice %s log!", "format")
88-
logger.Infof("this is a info %s log!", "format")
89-
logger.Debugf("this is a debug %s log!", "format")
90-
91-
// If set to asynchronous, the flush method must finally be invoked to ensure that all the logs are out
92-
logger.Flush()
93-
}
94-
```
95-
- ### console adapter
96-
```
97-
// config console
98-
consoleConfig := &go_logger.ConsoleConfig{
99-
Color: true, // text show color
100-
JsonFormat: true, // json format
101-
ShowFileLine: true, // when JsonFormat is false, console show file line, default false
102106
}
103-
// attach
104-
logger.Attach("console", go_logger.LOGGER_LEVEL_DEBUG, consoleConfig)
105107
```
106-
#### console color preview
108+
109+
## Console text with color effect
107110
![image](https://github.com/phachon/go-logger/blob/master/_example/images/console.png)
108111

109-
- ### file adapter
112+
## Customize Format output
110113

114+
Logger Message
115+
116+
| Field | Alias |Type | Comment | Example |
117+
| Timestamp | timestamp | int64 | unix timestamp| 1521791201 |
118+
| TimestampFormat | timestamp_format| string | timestamp format | 2018-3-23 15:46:41|
119+
| Millisecond | millisecond | int64 | millisecond | |
120+
| MillisecondFormat | millisecond_format| string | millisecond_format | 2018-3-23 15:46:41.970 |
121+
| Level | level| int | logger level | 1 |
122+
| LevelString | level_string | string | logger level string | Error |
123+
| Body | body | string | logger message body | this is a info log |
124+
| File | file | string | Call the file of the logger | main.go |
125+
| Line | line | int | The number of specific lines to call logger |64|
126+
| Function | function| string | The function name to call logger | main() |
127+
128+
If you want to customize the format of the log output ?
129+
130+
config format:
111131
```
112-
// config file
132+
consoleConfig := &go_logger.ConsoleConfig{
133+
Format: "%millisecond_format% [%level_string%] %body%"
134+
}
113135
fileConfig := &go_logger.FileConfig{
114-
Filename : "./test.log", // The file name of the log output does not exist automatically.
115-
// If you want to output different levels of logs to a file individually, configure the LevelFileName parameter.
116-
LevelFileName : map[int]string {
117-
go_logger.LOGGER_LEVEL_ERROR: "./error.log", // The error level log is written to the error.log file.
118-
go_logger.LOGGER_LEVEL_INFO: "./info.log", // The info level log is written to the info.log file.
119-
go_logger.LOGGER_LEVEL_DEBUG: "./debug.log", // The debug level log is written to the debug.log file.
120-
},
121-
MaxSize : 1024 * 1024, // max file size(kb)
122-
MaxLine : 100000, // max file line
123-
DateSlice : "d", // slice file by date, support "y", "m", "d", "h", default "" not slice
124-
JsonFormat: true, // json format
136+
Format: "%millisecond_format% [%level_string%] %body%"
125137
}
126-
logger.Attach("file", go_logger.LOGGER_LEVEL_DEBUG, fileConfig)
127138
```
128-
129-
- ### api adapter
130-
139+
output:
131140
```
132-
apiConfig := &go_logger.ApiConfig{
133-
Url: "http://127.0.0.1:8081/index.php", //request url address, not empty
134-
Method: "GET", //request method GET or POST
135-
Headers: map[string]string{}, //request headers, default empty
136-
IsVerify: false, //response is verify code, default false
137-
VerifyCode: 0, //verify code value, if isVerify is true, verifyCode is not be 0
138-
}
139-
logger.Attach("api", go_logger.LOGGER_LEVEL_DEBUG, apiConfig)
141+
2018-03-23 14:55:07.003 [Critical] this is a critical log!
140142
```
141143

144+
You can customize the format, Only needs to be satisfied Format: "%Logger Message Alias%"
145+
146+
## More adapter examples
147+
- [console](./_example/console.go)
148+
- [file](./_example/file.go)
149+
- [api](./_example/api.go)
150+
151+
152+
## Benchmark
153+
142154
## Reference
143155
beego/logs : github.com/astaxie/beego/logs
144156

_example/console.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ func main() {
1212

1313
consoleConfig := &go_logger.ConsoleConfig{
1414
Color: true,
15-
//JsonFormat: true,
16-
//ShowFileLine: true,
15+
JsonFormat: false,
16+
Format: "%millisecond_format% [%level_string%] [%file%:%line%] %body%",
1717
}
1818

1919
logger.Attach("console", go_logger.LOGGER_LEVEL_DEBUG, consoleConfig)

_example/file.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ func main() {
1818
MaxSize : 1024 * 1024,
1919
MaxLine : 10000,
2020
DateSlice : "d",
21-
JsonFormat: true,
21+
JsonFormat: false,
22+
Format: "%millisecond_format% [%level_string%] [%file%:%line%] %body%",
2223
}
2324
logger.Attach("file", go_logger.LOGGER_LEVEL_DEBUG, fileConfig)
2425
logger.SetAsync()

console.go

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package go_logger
33
import (
44
"sync"
55
"io"
6-
"strconv"
76
"github.com/fatih/color"
87
"os"
98
"encoding/json"
@@ -44,8 +43,22 @@ type ConsoleConfig struct {
4443
// is json format
4544
JsonFormat bool
4645

47-
// is show file
48-
ShowFileLine bool
46+
// jsonFormat is false, please input format string
47+
// if format is empty, default format "%millisecond_format% [%level_string%] %body%"
48+
//
49+
// Timestamp "%timestamp%"
50+
// TimestampFormat "%timestamp_format%"
51+
// Millisecond "%millisecond%"
52+
// MillisecondFormat "%millisecond_format%"
53+
// Level int "%level%"
54+
// LevelString "%level_string%"
55+
// Body string "%body%"
56+
// File string "%file%"
57+
// Line int "%line%"
58+
// Function "%function%"
59+
//
60+
// example: format = "%millisecond_format% [%level_string%] %body%"
61+
Format string
4962
}
5063

5164
func (cc *ConsoleConfig) Name() string {
@@ -71,30 +84,22 @@ func (adapterConsole *AdapterConsole) Init(consoleConfig Config) error {
7184
vc := reflect.ValueOf(consoleConfig)
7285
cc := vc.Interface().(*ConsoleConfig)
7386
adapterConsole.config = cc
87+
88+
if cc.JsonFormat == false && cc.Format == "" {
89+
cc.Format = defaultLoggerMessageFormat
90+
}
91+
7492
return nil
7593
}
7694

7795
func (adapterConsole *AdapterConsole) Write(loggerMsg *loggerMessage) error {
7896

79-
//timestamp := loggerMsg.Timestamp
80-
//timestampFormat := loggerMsg.TimestampFormat
81-
//millisecond := loggerMsg.Millisecond
82-
millisecondFormat := loggerMsg.MillisecondFormat
83-
body := loggerMsg.Body
84-
file := loggerMsg.File
85-
line := loggerMsg.Line
86-
levelString := loggerMsg.LevelString
87-
8897
msg := ""
8998
if adapterConsole.config.JsonFormat == true {
9099
jsonByte, _ := json.Marshal(loggerMsg)
91100
msg = string(jsonByte)
92101
}else {
93-
msg = millisecondFormat +" ["+ levelString + "] "
94-
if adapterConsole.config.ShowFileLine {
95-
msg += "[" + file + ":" + strconv.Itoa(line) + "] "
96-
}
97-
msg += body
102+
msg = loggerMessageFormat(adapterConsole.config.Format, loggerMsg)
98103
}
99104

100105
if adapterConsole.config.Color {

file.go

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package go_logger
33
import (
44
"sync"
55
"os"
6-
"strconv"
76
"path"
87
"strings"
98
"time"
@@ -72,6 +71,23 @@ type FileConfig struct {
7271

7372
// is json format
7473
JsonFormat bool
74+
75+
// jsonFormat is false, please input format string
76+
// if format is empty, default format "%millisecond_format% [%level_string%] %body%"
77+
//
78+
// Timestamp "%timestamp%"
79+
// TimestampFormat "%timestamp_format%"
80+
// Millisecond "%millisecond%"
81+
// MillisecondFormat "%millisecond_format%"
82+
// Level int "%level%"
83+
// LevelString "%level_string%"
84+
// Body string "%body%"
85+
// File string "%file%"
86+
// Line int "%line%"
87+
// Function "%function%"
88+
//
89+
// example: format = "%millisecond_format% [%level_string%] %body%"
90+
Format string
7591
}
7692

7793
func (fc *FileConfig) Name() string {
@@ -102,6 +118,10 @@ func (adapterFile *AdapterFile) Init(fileConfig Config) error {
102118
fc := vc.Interface().(*FileConfig)
103119
adapterFile.config = fc
104120

121+
if fc.JsonFormat == false && fc.Format == "" {
122+
fc.Format = defaultLoggerMessageFormat
123+
}
124+
105125
if len(adapterFile.config.LevelFileName) == 0 {
106126
if adapterFile.config.Filename == "" {
107127
return errors.New("config Filename can't be empty!")
@@ -231,16 +251,6 @@ func (fw *FileWriter) initFile() error {
231251
// write by config
232252
func (fw *FileWriter) writeByConfig(config *FileConfig, loggerMsg *loggerMessage) error {
233253

234-
//timestamp := loggerMsg.Timestamp
235-
//timestampFormat := loggerMsg.TimestampFormat
236-
//millisecond := loggerMsg.Millisecond
237-
millisecondFormat := loggerMsg.MillisecondFormat
238-
body := loggerMsg.Body
239-
file := loggerMsg.File
240-
line := loggerMsg.Line
241-
levelString := loggerMsg.LevelString
242-
243-
//fileWrite := adapterFile.write
244254
fw.lock.Lock()
245255
defer fw.lock.Unlock()
246256

@@ -269,9 +279,9 @@ func (fw *FileWriter) writeByConfig(config *FileConfig, loggerMsg *loggerMessage
269279
msg := ""
270280
if config.JsonFormat == true {
271281
jsonByte, _ := json.Marshal(loggerMsg)
272-
msg = string(jsonByte) + "\n"
282+
msg = string(jsonByte) + "\r\n"
273283
}else {
274-
msg = millisecondFormat +" ["+ levelString + "] [" + file + ":" + strconv.Itoa(line) + "] " + body + "\n"
284+
msg = loggerMessageFormat(config.Format, loggerMsg) + "\r\n"
275285
}
276286

277287
fw.writer.Write([]byte(msg))
@@ -395,7 +405,7 @@ func (fw *FileWriter) getFileObject(filename string) (file *os.File, err error)
395405
//return : fileSize(byte int64), error
396406
func (fw *FileWriter) getFileSize(filename string) (fileSize int64, err error) {
397407
fileInfo, err := os.Stat(filename)
398-
if(err != nil) {
408+
if err != nil {
399409
return fileSize, err
400410
}
401411

0 commit comments

Comments
 (0)