Skip to content

Commit

Permalink
Automated commit by GitLab CI/CD - Personal Bot
Browse files Browse the repository at this point in the history
  • Loading branch information
poniatowski-bot committed Nov 9, 2023
1 parent 3c15429 commit 12341d8
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 45 deletions.
64 changes: 37 additions & 27 deletions boillog.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package boillog

import (
"context"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strconv"
"time"

"golang.org/x/exp/slog"
)

// ///////////////////////////== Environment Variables ==////////////////////////////
Expand Down Expand Up @@ -40,41 +44,47 @@ func envAppName() string {

///////////////////////////////== Logging functions ==//////////////////////////////

// LogIt Boilerplate funtion that calls Logger, to write/prints logs
// Define a custom type to avoid collisions
type contextKey string

// Define constants for the key used
const (
FuncKey contextKey = "func"
)

// LogIt Boilerplate funtion that calls Logger, to write logs, and prints it if it fails to write it
func LogIt(logFunction string, logOutput string, message string) {
errCloseLogger := Logger(logFunction, logOutput, message)
logPath := filepath.Join(envLogLocation(), envAppName())
file, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println("Error opening log file:", err)
return
}
defer file.Close()
errCloseLogger := logger(logFunction, logOutput, message, file)
if errCloseLogger != nil {
log.Println(errCloseLogger)
}
}

// Logger This function is called by Logit and prints/writes logs
func Logger(logFunction string, logOutput string, message string) error {
currentDate := time.Now().Format("2006-01-02 15:04:05")
pathString := envLogLocation()
logName := envAppName()
path, _ := filepath.Abs(pathString)
err := os.MkdirAll(path, os.ModePerm)
if err == nil || os.IsExist(err) {
logFile, err := os.OpenFile(pathString+logName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer func() {
errClose := logFile.Close()
if errClose != nil {
log.Println(errClose)
}
}()
logger := log.New(logFile, "", log.LstdFlags)
logger.SetPrefix(currentDate)
logger.Print(logFunction + " [ " + logOutput + " ] ==> " + message)
} else {
return err
}
if logOutput != "INFO" {
fmt.Println("\t" + logFunction + " [ " + logOutput + " ] ==> " + message)
func logger(logFunction string, logOutput string, message string, w io.Writer) error {
handler := slog.NewTextHandler(w, nil)
logger := slog.New(handler)
ctx := context.Background()
ctx = context.WithValue(ctx, slog.TimeKey, time.Now())
ctx = context.WithValue(ctx, FuncKey, logFunction)
switch logOutput {
case "INFO":
logger.InfoContext(ctx, message)
case "WARNING":
logger.WarnContext(ctx, message)
case "ERROR":
logger.ErrorContext(ctx, message)
default:
logger.InfoContext(ctx, message)
}

return nil
}

Expand Down
25 changes: 7 additions & 18 deletions boillog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
func TestEnvProfiler(t *testing.T) {
os.Setenv("PROFILER", "true")
defer os.Unsetenv("PROFILER")

expected := "true"
if result := envProfiler(); result != expected {
t.Errorf("Expected PROFILER to be %s, got %s", expected, result)
Expand All @@ -22,7 +21,6 @@ func TestEnvProfiler(t *testing.T) {
func TestEnvLogLocation(t *testing.T) {
os.Setenv("LOGLOCATION", "/tmp/")
defer os.Unsetenv("LOGLOCATION")

expected := "/tmp/"
if result := envLogLocation(); result != expected {
t.Errorf("Expected LOGLOCATION to be %s, got %s", expected, result)
Expand All @@ -33,49 +31,40 @@ func TestEnvLogLocation(t *testing.T) {
func TestEnvAppName(t *testing.T) {
os.Setenv("APP_NAME", "testapp.log")
defer os.Unsetenv("APP_NAME")

expected := "testapp.log"
if result := envAppName(); result != expected {
t.Errorf("Expected APP_NAME to be %s, got %s", expected, result)
}
}

// TestLogger tests the Logger function for successful log creation.
func TestLogger(t *testing.T) {
// TestLogIt tests the LogIt function for successful log creation.
func TestLogIt(t *testing.T) {
testLogLocation := "/tmp/"
testLogName := "test.log"

// Set the environment variable for testing.
os.Setenv("LOGLOCATION", testLogLocation)
os.Setenv("APP_NAME", testLogName)
defer func() {
os.Unsetenv("LOGLOCATION")
os.Unsetenv("APP_NAME")
os.Remove(testLogLocation + testLogName) // Clean up after the test.
}()

if err := Logger("TestLogger", "INFO", "This is a test log message."); err != nil {
t.Errorf("Logger should not have returned an error: %v", err)
}

// Read the log file and check contents.
LogIt("TestLogIt", "INFO", "This is a test log message.")
content, err := os.ReadFile(testLogLocation + testLogName)
if err != nil {
t.Fatalf("Error reading log file: %v", err)
}

if !strings.Contains(string(content), "This is a test log message.") {
logContent := string(content)
if !strings.Contains(logContent, "This is a test log message.") {
t.Errorf("Log file should contain the test log message.")
}
}

// TestTrackTime tests the TrackTime function's profiling capability.
func TestTrackTime(t *testing.T) {
startTime := time.Now()
time.Sleep(10 * time.Millisecond)
time.Sleep(100 * time.Millisecond)
elapsed := TrackTime("TestTrackTime", startTime)

if elapsed < 10*time.Millisecond {
if elapsed < 100*time.Millisecond {
t.Errorf("TrackTime should have reported an elapsed time of at least 10ms, got %v", elapsed)
}
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/APoniatowski/boillog

go 1.21.3

require golang.org/x/exp v0.0.0-20231108232855-2478ac86f678
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w=
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE=

0 comments on commit 12341d8

Please sign in to comment.