Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add structure logging handler for package glog #2919

Merged
merged 3 commits into from
Sep 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions database/gdb/gdb_result.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,6 @@ func (r *SqlResult) MustGetInsertId() int64 {
// driver may support this.
// Also, See sql.Result.
func (r *SqlResult) RowsAffected() (int64, error) {
if r.Result == nil {
return 0, nil
}
if r.Affected > 0 {
return r.Affected, nil
}
Expand Down
41 changes: 11 additions & 30 deletions os/glog/glog_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func (l *Logger) getFilePath(now time.Time) string {
}

// print prints `s` to defined writer, logging file or passed `std`.
func (l *Logger) print(ctx context.Context, level int, stack string, values ...interface{}) {
func (l *Logger) print(ctx context.Context, level int, stack string, values ...any) {
// Lazy initialize for rotation feature.
// It uses atomic reading operation to enhance the performance checking.
// It here uses CAP for performance and concurrent safety.
Expand All @@ -117,6 +117,7 @@ func (l *Logger) print(ctx context.Context, level int, stack string, values ...i
Color: defaultLevelColor[level],
Level: level,
Stack: stack,
Values: values,
}
)

Expand All @@ -126,7 +127,7 @@ func (l *Logger) print(ctx context.Context, level int, stack string, values ...i
} else if defaultHandler != nil {
input.handlers = []Handler{defaultHandler}
}
input.handlers = append(input.handlers, defaultPrintHandler)
input.handlers = append(input.handlers, doFinalPrint)

// Time.
timeFormat := ""
Expand Down Expand Up @@ -205,24 +206,6 @@ func (l *Logger) print(ctx context.Context, level int, stack string, values ...i
}
}
}
var tempStr string
for _, v := range values {
tempStr = gconv.String(v)
if len(input.Content) > 0 {
if input.Content[len(input.Content)-1] == '\n' {
// Remove one blank line(\n\n).
if len(tempStr) > 0 && tempStr[0] == '\n' {
input.Content += tempStr[1:]
} else {
input.Content += tempStr
}
} else {
input.Content += " " + tempStr
}
} else {
input.Content = tempStr
}
}
if l.config.Flags&F_ASYNC > 0 {
input.IsAsync = true
err := asyncPool.Add(ctx, func(ctx context.Context) {
Expand Down Expand Up @@ -265,9 +248,7 @@ func (l *Logger) doDefaultPrint(ctx context.Context, input *HandlerInput) *bytes
// printToWriter writes buffer to writer.
func (l *Logger) printToWriter(ctx context.Context, input *HandlerInput) *bytes.Buffer {
if l.config.Writer != nil {
var (
buffer = input.getRealBuffer(l.config.WriterColorEnable)
)
var buffer = input.getRealBuffer(l.config.WriterColorEnable)
if _, err := l.config.Writer.Write(buffer.Bytes()); err != nil {
intlog.Errorf(ctx, `%+v`, err)
}
Expand All @@ -283,7 +264,7 @@ func (l *Logger) printToStdout(ctx context.Context, input *HandlerInput) *bytes.
err error
buffer = input.getRealBuffer(!l.config.StdoutColorDisabled)
)
// This will lose color in Windows os system.
// This will lose color in Windows os system. DO NOT USE.
// if _, err := os.Stdout.Write(input.getRealBuffer(true).Bytes()); err != nil {

// This will print color in Windows os system.
Expand Down Expand Up @@ -372,23 +353,23 @@ func (l *Logger) getOpenedFilePointer(ctx context.Context, path string) *gfpool.
}

// printStd prints content `s` without stack.
func (l *Logger) printStd(ctx context.Context, level int, value ...interface{}) {
l.print(ctx, level, "", value...)
func (l *Logger) printStd(ctx context.Context, level int, values ...interface{}) {
l.print(ctx, level, "", values...)
}

// printStd prints content `s` with stack check.
func (l *Logger) printErr(ctx context.Context, level int, value ...interface{}) {
func (l *Logger) printErr(ctx context.Context, level int, values ...interface{}) {
var stack string
if l.config.StStatus == 1 {
stack = l.GetStack()
}
// In matter of sequence, do not use stderr here, but use the same stdout.
l.print(ctx, level, stack, value...)
l.print(ctx, level, stack, values...)
}

// format formats `values` using fmt.Sprintf.
func (l *Logger) format(format string, value ...interface{}) string {
return fmt.Sprintf(format, value...)
func (l *Logger) format(format string, values ...interface{}) string {
return fmt.Sprintf(format, values...)
}

// PrintStack prints the caller stack,
Expand Down
36 changes: 31 additions & 5 deletions os/glog/glog_logger_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"bytes"
"context"
"time"

"github.com/gogf/gf/v2/util/gconv"
)

// Handler is function handler for custom logging content outputs.
Expand All @@ -31,6 +33,7 @@ type HandlerInput struct {
TraceId string // Trace id, only available if OpenTelemetry is enabled.
Prefix string // Custom prefix string for logging content.
Content string // Content is the main logging content without error stack string produced by logger.
Values []any // The passed un-formatted values array to logger.
Stack string // Stack string produced by logger, only available if Config.StStatus configured.
IsAsync bool // IsAsync marks it is in asynchronous logging.
}
Expand All @@ -43,9 +46,9 @@ type internalHandlerInfo struct {
// defaultHandler is the default handler for package.
var defaultHandler Handler

// defaultPrintHandler is a handler for logging content printing.
// doFinalPrint is a handler for logging content printing.
// This handler outputs logging content to file/stdout/write if any of them configured.
func defaultPrintHandler(ctx context.Context, in *HandlerInput) {
func doFinalPrint(ctx context.Context, in *HandlerInput) {
buffer := in.Logger.doDefaultPrint(ctx, in)
if in.Buffer.Len() == 0 {
in.Buffer = buffer
Expand Down Expand Up @@ -113,13 +116,36 @@ func (in *HandlerInput) getDefaultBuffer(withColor bool) *bytes.Buffer {
in.addStringToBuffer(buffer, in.CallerPath)
}
}

if in.Content != "" {
if in.Stack != "" {
in.addStringToBuffer(buffer, in.Content+"\nStack:\n"+in.Stack)
in.addStringToBuffer(buffer, in.Content)
}

// Convert values string content.
var valueContent string
for _, v := range in.Values {
valueContent = gconv.String(v)
if len(valueContent) == 0 {
continue
}
if buffer.Len() > 0 {
if buffer.Bytes()[buffer.Len()-1] == '\n' {
// Remove one blank line(\n\n).
if valueContent[0] == '\n' {
valueContent = valueContent[1:]
}
buffer.WriteString(valueContent)
} else {
buffer.WriteString(" " + valueContent)
}
} else {
in.addStringToBuffer(buffer, in.Content)
buffer.WriteString(valueContent)
}
}

if in.Stack != "" {
in.addStringToBuffer(buffer, "\nStack:\n"+in.Stack)
}
// avoid a single space at the end of a line.
buffer.WriteString("\n")
return buffer
Expand Down
25 changes: 24 additions & 1 deletion os/glog/glog_logger_handler_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"context"

"github.com/gogf/gf/v2/internal/json"
"github.com/gogf/gf/v2/util/gconv"
)

// HandlerOutputJson is the structure outputting logging content as single json.
Expand All @@ -18,8 +19,8 @@ type HandlerOutputJson struct {
TraceId string `json:",omitempty"` // Trace id, only available if tracing is enabled.
CtxStr string `json:",omitempty"` // The retrieved context value string from context, only available if Config.CtxKeys configured.
Level string `json:""` // Formatted level string, like "DEBU", "ERRO", etc. Eg: ERRO
CallerFunc string `json:",omitempty"` // The source function name that calls logging, only available if F_CALLER_FN set.
CallerPath string `json:",omitempty"` // The source file path and its line number that calls logging, only available if F_FILE_SHORT or F_FILE_LONG set.
CallerFunc string `json:",omitempty"` // The source function name that calls logging, only available if F_CALLER_FN set.
Prefix string `json:",omitempty"` // Custom prefix string for logging content.
Content string `json:""` // Content is the main logging content, containing error stack string produced by logger.
Stack string `json:",omitempty"` // Stack string produced by logger, only available if Config.StStatus configured.
Expand All @@ -38,6 +39,28 @@ func HandlerJson(ctx context.Context, in *HandlerInput) {
Content: in.Content,
Stack: in.Stack,
}
// Convert values string content.
var valueContent string
for _, v := range in.Values {
valueContent = gconv.String(v)
if len(valueContent) == 0 {
continue
}
if len(output.Content) > 0 {
if output.Content[len(output.Content)-1] == '\n' {
// Remove one blank line(\n\n).
if valueContent[0] == '\n' {
valueContent = valueContent[1:]
}
output.Content += valueContent
} else {
output.Content += " " + valueContent
}
} else {
output.Content += valueContent
}
}
// Output json content.
jsonBytes, err := json.Marshal(output)
if err != nil {
panic(err)
Expand Down
Loading
Loading