Skip to content

Commit

Permalink
Merge pull request #25 from AndrewDonelson/develop
Browse files Browse the repository at this point in the history
Update master to latest
  • Loading branch information
AndrewDonelson authored Dec 20, 2019
2 parents 9231dbd + b9a3090 commit 21a482e
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 97 deletions.
31 changes: 22 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ This will either Install or Update the package.

## Example

Example [program](example/example.go) demonstrates how to use the logger. See below for *formatting* instructions.
Example [program](examples/basic/main.go) demonstrates how to use the logger. See below for *formatting* instructions.

```go
package main
Expand Down Expand Up @@ -84,25 +84,38 @@ type Options struct {

### Creating New Logger

Default (minumum)
There is no need to manually create a logger. Simply import golog and start using.

```go
// Create a logger with all default options
log, err := golog.NewLogger(nil)
if err != nil {
panic(err) // Check for error
}
golog.Log.SetModule("myapp")
err := RunSomeFunction()
if err != nil {
golog.Log.ErrorE(err)
}
```

Typical
#### Default (minumum)

```go
// Create a logger with all default options
log, err := golog.NewLogger(nil)
if err != nil {
panic(err) // Check for error
}
log.SetModule("rpc.ServiceName")
```

#### Typical

```go
// create a new golag logger
log, err := golog.NewLogger(&golog.Options{Module: "myapp"})
if err != nil {
panic(err) // Check for error
}
// You can set the Environment here, or in the above NewLogger() call but suggested way
// is to use an OS Environment variable named "BUILD_ENV" to set either dev or qa.
// Anything else would be considered production
log.SetEnvironment(golog.EnvProduction)
```

Custom
Expand Down
Binary file modified examples/basic/basic.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
51 changes: 21 additions & 30 deletions examples/basic/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,55 +4,46 @@ import (
"github.com/AndrewDonelson/golog"
)

func doLogs(log *golog.Logger) {
func doLogs() {
method := "doLogs"
log.Trace(method, "example.go", 7)
log.SetFunction(method)
golog.Log.Trace(method, "example.go", 7)
golog.Log.SetFunction(method)

// Critically log critical
log.Critical("This is Critical message!")
golog.Log.Critical("This is Critical message!")
// Show the error
log.Error("This is Error message!")
golog.Log.Error("This is Error message!")
// Show the success
log.Success("This is Success message!")
golog.Log.Success("This is Success message!")
// Give the Warning
log.Warning("This is Warning message!")
golog.Log.Warning("This is Warning message!")
// Notice
log.Notice("This is Notice message!")
golog.Log.Notice("This is Notice message!")
// Show the info
log.Info("This is Info message, Fatal & Panic skipped!")
golog.Log.Info("This is Info message, Fatal & Panic skipped!")
// Debug
log.Debug("This is Debug message!")
golog.Log.Debug("This is Debug message!")
}

func main() {
// Get the instance for logger class
// Third option is optional and is instance of type io.Writer, defaults to os.Stderr
println("\nProduction Output: as Log")
log, err := golog.NewLogger(&golog.Options{Module: "prod-example"})
if err != nil {
panic(err) // Check for error
}
log.SetEnvironment(golog.EnvProduction)
doLogs(log)
golog.Log.SetModuleName("prod-example")
golog.Log.SetEnvironment(golog.EnvProduction)
doLogs()

println("\nProduction Output: as JSON")
log.UseJSONForProduction()
doLogs(log)
golog.Log.UseJSONForProduction()
doLogs()

println("\nTest/QA Output:")
log, err = golog.NewLogger(&golog.Options{Module: "qa-example"})
if err != nil {
panic(err) // Check for error
}
log.SetEnvironment(golog.EnvQuality)
doLogs(log)
golog.Log.SetModuleName("qa-example")
golog.Log.SetEnvironment(golog.EnvQuality)
doLogs()

println("\nDevelopment Output:")
log, err = golog.NewLogger(&golog.Options{Module: "dev-example"})
if err != nil {
panic(err) // Check for error
}
log.SetEnvironment(golog.EnvDevelopment)
doLogs(log)
golog.Log.SetModuleName("dev-example")
golog.Log.SetEnvironment(golog.EnvDevelopment)
doLogs()
}
77 changes: 37 additions & 40 deletions golog.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"runtime"
"sync/atomic"
"time"
"log"
)

const (
Expand Down Expand Up @@ -71,13 +72,13 @@ const (
White
)

// Log Level
// Log Level. Panic is not included as a level.
const (
RawLevel = iota + 1 // None
CriticalLevel // Magneta 35
CriticalLevel // Magneta 35 - Critical & Fatal Levels are same
ErrorLevel // Red 31
WarningLevel // Yellow 33
SuccessLevel // Green 32
WarningLevel // Yellow 33
NoticeLevel // Cyan 36
InfoLevel // White 37
DebugLevel // Blue 34
Expand All @@ -96,7 +97,9 @@ func init() {
var err error
Log, err = NewLogger(nil)
if err != nil {
panic(fmt.Sprintf("Error creating logger: %v", err))
// Removed panic as program execution should not halt for alog issue. Replaced with
// golang log Fatal event for developer to recitfy.
log.Fatalf("golog:init error: %v", err)
}
Log.Printf("Default Log intialized for %s", Log.Options.EnvAsString())
}
Expand Down Expand Up @@ -163,10 +166,7 @@ func (l *Logger) logInternal(lvl LogLevel, message string, pos int) {
Duration: l.timeElapsed(l.timer),
//format: formatString,
}
err := l.worker.Log(lvl, 2, info)
if err != nil {
panic(err)
}
l.worker.Log(lvl, 2, info)
}

func (l *Logger) traceInternal(message string, pos int) {
Expand All @@ -184,10 +184,7 @@ func (l *Logger) traceInternal(message string, pos int) {
Duration: l.timeElapsed(l.timer),
//format: formatString,
}
err := l.worker.Log(info.Level, 2, info)
if err != nil {
panic(err)
}
l.worker.Log(info.Level, 2, info)
}

// SetModuleName sets the name of the module being logged
Expand Down Expand Up @@ -246,42 +243,42 @@ func (l *Logger) Trace(name, file string, line int) {
defer l.timeLog(name)
}

// Fatal is just like func l.Critical logger except that it is followed by exit to program
func (l *Logger) Fatal(message string) {
// Panic is just like func l.Critical except that it is followed by a call to panic
func (l *Logger) Panic(message string) {
l.logInternal(CriticalLevel, message, 2)
if l.worker.GetEnvironment() == EnvTesting {
return
}
os.Exit(1)
panic(message)
}

// FatalE logs a error at Fatallevel
func (l *Logger) FatalE(err error) {
l.Fatal(err.Error())
// PanicE logs a error at Criticallevel
func (l *Logger) PanicE(err error) {
l.Panic(err.Error())
}

// Fatalf is just like func l.CriticalF logger except that it is followed by exit to program
func (l *Logger) Fatalf(format string, a ...interface{}) {
l.Fatal(fmt.Sprintf(format, a...))
// Panicf is just like func l.CriticalF except that it is followed by a call to panic
func (l *Logger) Panicf(format string, a ...interface{}) {
l.Panic(fmt.Sprintf(format, a...))
}

// Panic is just like func l.Critical except that it is followed by a call to panic
func (l *Logger) Panic(message string) {
// Fatal is just like func l.Critical logger except that it is followed by exit to program
func (l *Logger) Fatal(message string) {
l.logInternal(CriticalLevel, message, 2)
if l.worker.GetEnvironment() == EnvTesting {
return
}
panic(message)
os.Exit(1)
}

// PanicE logs a error at Criticallevel
func (l *Logger) PanicE(err error) {
l.Panic(err.Error())
// FatalE logs a error at Fatallevel
func (l *Logger) FatalE(err error) {
l.Fatal(err.Error())
}

// Panicf is just like func l.CriticalF except that it is followed by a call to panic
func (l *Logger) Panicf(format string, a ...interface{}) {
l.Panic(fmt.Sprintf(format, a...))
// Fatalf is just like func l.CriticalF logger except that it is followed by exit to program
func (l *Logger) Fatalf(format string, a ...interface{}) {
l.Fatal(fmt.Sprintf(format, a...))
}

// Critical logs a message at a Critical Level
Expand Down Expand Up @@ -314,16 +311,6 @@ func (l *Logger) Errorf(format string, a ...interface{}) {
l.logInternal(ErrorLevel, fmt.Sprintf(format, a...), 2)
}

// Success logs a message at Success level
func (l *Logger) Success(message string) {
l.logInternal(SuccessLevel, message, 2)
}

// Successf logs a message at Success level using the same syntax and options as fmt.Printf
func (l *Logger) Successf(format string, a ...interface{}) {
l.logInternal(SuccessLevel, fmt.Sprintf(format, a...), 2)
}

// Warning logs a message at Warning level
func (l *Logger) Warning(message string) {
l.logInternal(WarningLevel, message, 2)
Expand All @@ -339,6 +326,16 @@ func (l *Logger) Warningf(format string, a ...interface{}) {
l.logInternal(WarningLevel, fmt.Sprintf(format, a...), 2)
}

// Success logs a message at Success level
func (l *Logger) Success(message string) {
l.logInternal(SuccessLevel, message, 2)
}

// Successf logs a message at Success level using the same syntax and options as fmt.Printf
func (l *Logger) Successf(format string, a ...interface{}) {
l.logInternal(SuccessLevel, fmt.Sprintf(format, a...), 2)
}

// Notice logs a message at Notice level
func (l *Logger) Notice(message string) {
l.logInternal(NoticeLevel, message, 2)
Expand Down
16 changes: 8 additions & 8 deletions golog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,14 +318,14 @@ func TestLogLevel(t *testing.T) {
ErrorLevel,
"Error logging",
},
{
SuccessLevel,
"Success logging",
},
{
WarningLevel,
"Warning logging",
},
{
SuccessLevel,
"Success logging",
},
{
NoticeLevel,
"Notice Logging",
Expand All @@ -343,31 +343,31 @@ func TestLogLevel(t *testing.T) {
var buf bytes.Buffer

log, err := NewLogger(&Options{
Module: "pkgname",
Out: &buf,
Environment: 0,
Environment: EnvDevelopment,
UseColor: ClrNotSet,
})
if err != nil || log == nil {
t.Error(err)
return
}
log.SetModuleName("pkgname")

for i, test := range tests {
log.SetLogLevel(test.level)

log.Critical("Log Critical")
log.Error("Log Error")
log.Success("Log Success")
log.Warning("Log Warning")
log.Success("Log Success")
log.Notice("Log Notice")
log.Info("Log Info")
log.Debug("Log Debug")

// Count output lines from logger
count := strings.Count(buf.String(), "\n")
if i+1 != count {
t.Error()
t.Errorf("Log events expected %d have %d", i+1, count)
}
buf.Reset()
}
Expand Down
7 changes: 2 additions & 5 deletions info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,8 @@ func TestNewInfo(t *testing.T) {
Filename: filename,
Line: line,
}
err = log.worker.Log(CriticalLevel, 2, info)
if err != nil {
t.Error(err)
return
}
log.worker.Log(CriticalLevel, 2, info)

// "unknown 2019-10-15 19:20:51 INF - Hello World!"
want := fmt.Sprintf("[unknown] #88 %s INF Hello World!\n", time.Now().Format("2006-01-02 15:04:05"))
have := buf.String()
Expand Down
2 changes: 1 addition & 1 deletion options.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ type Options struct {
Module string // Name of running module
Environment Environment // Override default handling
UseColor ColorMode // Enable color (override) default handling
SmartError bool // Extended error that adapts by envionment
SmartError bool // Extended error that adapts by environment
Out io.Writer // Where to write output
FmtProd string // for use with production environment
FmtDev string // for use with development environment
Expand Down
9 changes: 5 additions & 4 deletions worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,14 @@ func (w *Worker) SetOutput(out io.Writer) {
}

// Log Function of Worker class to log a string based on level
func (w *Worker) Log(level LogLevel, calldepth int, info *Info) error {
func (w *Worker) Log(level LogLevel, calldepth int, info *Info) {
info.Function = w.function

// Support RawLevel on any environment
clr := w.color
if level != RawLevel {
if w.level < level {
return nil
return
}
} else {
clr = ClrDisabled
Expand All @@ -110,9 +110,10 @@ func (w *Worker) Log(level LogLevel, calldepth int, info *Info) error {
buf.Write([]byte(colors[level]))
buf.Write([]byte(info.Output(w.format)))
buf.Write([]byte("\033[0m"))
return w.Minion.Output(calldepth+1, buf.String())
_ = w.Minion.Output(calldepth+1, buf.String())
return
}

// Regular no color output
return w.Minion.Output(calldepth+1, info.Output(w.format))
_ = w.Minion.Output(calldepth+1, info.Output(w.format))
}

0 comments on commit 21a482e

Please sign in to comment.