Skip to content
core-goPublic

About

No description or website provided.

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Latest commit

 

History

38 Commits

Folders and files

Repository files navigation

log

A Go utility library that provides logging adapters and supporting infrastructure for application services. The source is organized as a set of focused packages: a Logrus-based root logger, a Zap adapter, HTTP request/response logging for several web frameworks, an outbound HTTP client, Google Cloud Pub/Sub helpers, and small utility packages.

This README describes the implementation in the supplied source archive. The archive does not contain a go.mod file or Go test files, so it does not establish dependency versions, a minimum Go version, or a passing test/build status.

Contents

Capabilities

Area What it provides
Structured application logging Context-aware Logrus and Zap helpers, fields, formatted messages and duration fields
Output configuration JSON formatting, field-name mapping, log levels and optional caller-supplied rotating writers
HTTP server logging Request/response body, status, byte count and elapsed-time logging for net/http, Gin, Echo v4 and Echo v3
Log masking Callback-based masking of JSON request and response fields; request values can also be masked before being put in the request context
Outbound HTTP JSON-oriented GET/POST/PUT/PATCH/DELETE helpers, TLS client setup, Basic authentication headers and configurable logging callbacks
HTTP log publishing POST log payloads to an HTTP endpoint, optionally asynchronously and with retry delays
Google Cloud Pub/Sub Client creation, topic publishing, topic settings, permission checks and a health checker
Small helpers String masking, snake-case-to-camel-case conversion, log filename generation and directory creation

Package map

Import path Declared Go package Responsibility
github.com/core-go/log log Logrus initialization, context fields, level helpers, structured fields and duration logging
github.com/core-go/log/zap log Zap initialization and context-aware logging helpers
github.com/core-go/log/middleware middleware net/http logging middleware, response-writer wrappers, formatters, masking and panic recovery
github.com/core-go/log/gin gin Gin request/response logger and context-building middleware
github.com/core-go/log/echo echo Echo v4 request/response logger and context-building middleware
github.com/core-go/log/echo/v3 echo Adapter for the older Echo v3 import path
github.com/core-go/log/client client Outbound HTTP client creation, JSON request helpers, response decoding and HTTP errors
github.com/core-go/log/http http HTTP-based log publisher with optional retry and asynchronous sending
github.com/core-go/log/pubsub pubsub Google Cloud Pub/Sub client, publisher and health checker
github.com/core-go/log/strings strings String masking helpers
github.com/core-go/log/convert convert Camel-case conversion helpers

The framework integrations are separate packages. Import only the integrations used by an application; using the root logger does not require importing Gin, Echo or Google Cloud packages.

Installation and dependencies

In a Go module that can resolve the repository, add the library with:

go get github.com/core-go/log

The source archive supplied for this README has no go.mod, so exact versions cannot be inferred from it. External dependencies are package-specific:

Package External dependency visible in source
Root package github.com/sirupsen/logrus
/zap go.uber.org/zap
/gin github.com/gin-gonic/gin
/echo github.com/labstack/echo/v4
/echo/v3 github.com/labstack/echo (older Echo module path)
/pubsub cloud.google.com/go/pubsub, cloud.google.com/go/iam, google.golang.org/api/option
/client, /http, /middleware, /strings, /convert Standard library only in the supplied source

Dependency versions should be selected to match the application and the version of this library being used. In particular, the Echo v3 and Echo v4 adapters target different major-version import paths.

Root logger: Logrus

The root package is declared as package log and wraps Logrus. Initialize configures a new *logrus.Logger and also configures Logrus's package-global standard logger, which is what the convenience functions use.

Initialize

package main

import (
    "context"
    "time"

    applog "github.com/core-go/log"
)

func main() {
    applog.Initialize(applog.Config{
        Level:           "info",
        TimestampFormat: time.RFC3339Nano,
    })

    applog.Info(context.Background(), "service started")
    applog.Infof(context.Background(), "listening on %s", ":8080")
}

Config fields:

Field Meaning in the implementation
Level Logrus level parsed by logrus.ParseLevel (for example debug, info, warn, error)
Output File/location string passed to the optional writer factory; when no writer factory is supplied, this field alone does not add a file writer
Duration Name used for duration fields; defaults to duration
Fields Comma-separated context keys whose non-empty string values are copied into log fields
FieldMap Context key expected to contain a map[string]interface{}; its entries are copied into log fields
Map Optional logrus.FieldMap used by the JSON formatter
TimestampFormat JSON timestamp layout; defaults to 2006-01-02T15:04:05.000Z0700

The optional writer factory has this shape:

func(logLocation string, rotationTime time.Duration) (io.Writer, func() error)

When Output is non-empty and a factory is supplied, the returned writer is combined with os.Stderr. The factory is called with a 24-hour rotation interval. The returned close function is registered as a Logrus exit handler. The library does not include a concrete rotating-file implementation in the root package; the application supplies it.

Log methods

The common level helpers accept a context.Context and variadic message arguments:

applog.Trace(ctx, "trace message")
applog.Debug(ctx, "debug message")
applog.Info(ctx, "information")
applog.Warn(ctx, "warning")
applog.Error(ctx, "operation failed")

applog.Infof(ctx, "user %s signed in", userID)
applog.Errorf(ctx, "request failed: %v", err)

There are corresponding Tracef, Debugf, Infof, Warnf, Errorf, Fatalf and Panicf methods, plus Log and Logf for a caller-supplied logrus.Level.

For structured fields, use LogWithFields or the level-specific helpers:

applog.InfoWithFields(ctx, "user signed in", map[string]interface{}{
    "userId": userID,
    "source": "web",
})

applog.ErrorfWithFields(ctx, map[string]interface{}{
    "userId": userID,
}, "could not load user: %v", err)

Other related helpers include BuildLogFields, LogfWithFields, TraceWithFields, DebugWithFields, InfoWithFields, WarnWithFields, ErrorWithFields, FatalWithFields, PanicWithFields, and the *Fields / Log* convenience families.

Context fields

The root logger enriches every event with values from the supplied context:

  • If Config.FieldMap is set, the value at that context key is expected to be map[string]interface{}; each key/value pair is copied into the event.
  • Each name in Config.Fields is looked up separately. Only non-empty values of type string are copied.
  • Duration helpers add elapsed milliseconds under the configured Duration key.

A context passed to these methods must be non-nil because the implementation calls ctx.Value. Treat context values as logging metadata, not as a replacement for explicit function parameters.

Logger access and level checks

  • Logger() returns the *logrus.Logger created by the most recent Initialize call.
  • IsTraceEnable, IsDebugEnable, IsInfoEnable, IsWarnEnable and IsErrorEnable query the Logrus package-global logger's level.
  • Key(logger) returns the field-map key mapping when the supplied logger uses *logrus.JSONFormatter; otherwise it returns nil.
  • Fatal and Panic inherit the termination/panic behavior of Logrus. They should not be used as ordinary error-reporting calls.

Zap adapter

The /zap package is a separate implementation built on Uber Zap. Its declared package name is also log, so use an explicit import alias to avoid confusion with the root package and the standard library's log package.

import (
    "context"

    zapcore "go.uber.org/zap"
    zaplog "github.com/core-go/log/zap"
)

func run(ctx context.Context) error {
    logger, err := zaplog.Initialize(zaplog.Config{
        Level:  "debug",
        Fields: "requestId",
    })
    if err != nil {
        return err
    }
    defer logger.Sync()

    zaplog.Info(ctx, "request completed", zapcore.String("requestId", "req-123"))
    return nil
}

The API exposes:

  • Initialize and InitializeWithWriter to construct and store the package logger.
  • SetLogger to install an externally created *zap.Logger.
  • Logger to retrieve the package logger.
  • Level helpers such as Debug, Info, Warn, Error, Fatal, Panic and DPanic, plus formatted and field-map variants.
  • DebugDuration and InfoDuration to record elapsed milliseconds.
  • BuildLogFields and AppendFields to translate maps/context values into Zap fields.

Zap configuration

zap.Config supports Level, Duration, Fields, FieldMap, Map, CallerLevel, CallerSkip, Output and MaxSize.

Map is a *FieldMap that can customize the JSON keys for time, level, logger name, caller, function, message and stack trace. Defaults include time, level, logger and msg. The encoder uses JSON output and ISO-8601 time encoding in the supplied implementation.

CallerLevel is a comma-separated list of Zap levels for which the custom core captures the caller. If omitted, the implementation selects error and panic levels. CallerSkip adjusts the caller frame lookup.

For file output, use InitializeWithWriter and provide a factory with this shape:

func(logLocation string, rotationTime time.Duration, maxSize int64) (io.Writer, func() error)

The supplied source combines the returned writer with standard output. MaxSize accepts integer byte-size strings with B, KB, MB or GB units, such as 20MB.

The package also contains NewWriter, GetWriteSyncer, NewLogTraceLevelCore, SizeOfFile, and file-name/path helpers for applications that need lower-level Zap customization.

HTTP server request/response logging

The server logging implementations share a similar design across three integrations:

  • middleware: standard net/http handlers.
  • gin: Gin middleware.
  • echo: Echo v4 middleware.
  • echo/v3: Echo v3 middleware.

Each package defines its own LogConfig, Formatter, StructuredLogger and MaskLogger types. They are intentionally package-local rather than one shared configuration type.

Standard net/http example

package main

import (
    "context"
    "net/http"

    applog "github.com/core-go/log"
    logmw "github.com/core-go/log/middleware"
)

func main() {
    applog.Initialize(applog.Config{Level: "info"})

    config := logmw.LogConfig{
        Log:           true,
        Build:         true,
        Uri:           "uri",
        Method:        "method",
        RemoteIp:      "remoteIp",
        Request:       "request",
        Response:      "response",
        ResponseStatus:"status",
        Duration:      "duration",
        Size:          "size",
    }

    formatter := logmw.NewLogger()
    logRequest := func(ctx context.Context, message string, fields map[string]interface{}) {
        applog.InfoWithFields(ctx, message, fields)
    }

    mux := http.NewServeMux()
    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        _, _ = w.Write([]byte(`{"ok":true}`))
    })

    handler := logmw.Logger(config, logRequest, formatter)(mux)
    _ = http.ListenAndServe(":8080", handler)
}

The middleware buffers request/response data when configured so it can add body, response status, response size and elapsed milliseconds to the log event. It restores a buffered request body so the next handler can still read it. Build: true enables the built-in request metadata fields whose key names are configured in LogConfig.

Formatter and masking choices

Formatter is an interface with LogRequest and LogResponse methods. The package supplies:

  • NewLogger: standard structured formatter. Its optional sending variant can marshal the event to JSON and pass it to a caller-supplied send function.
  • NewLoggerWithJsonFormat: additionally attempts to decode configured request/response bodies into JSON objects for logging.
  • NewLoggerWithSending: enables JSON sending and accepts an optional mapping for the level, time and msg keys.
  • NewMaskLogger and NewMaskLoggerWithSending: apply caller-supplied request and response masking callbacks to JSON object bodies before logging/sending.

A masking callback has this shape:

func(map[string]interface{})

It receives a decoded JSON object and is expected to modify it in place. The mask logger is not a general-purpose secret scrubber for arbitrary binary or non-JSON payloads. Provide non-nil callbacks when the relevant body may be decoded and masked.

LogConfig fields

The middleware, gin, echo and echo/v3 configurations expose substantially the same fields:

Field Purpose visible in the implementation
Log Enables/disables request logging; default false
Separate For eligible requests, emits request and response as separate events instead of one combined event
Build Enables configured built-in request metadata fields
Uri, ReqId, Scheme, Proto, Method, RemoteAddr, RemoteIp, UserAgent Field names for URI, request ID, scheme, protocol, method, remote address/IP and user agent
Request, Response Field names used for request and response body content
ResponseStatus, Size, Duration Field names used for status, bytes written and elapsed milliseconds
Skips Comma-separated URI skip values processed by the package's suffix comparison
Map Maps context field names to JSON body paths; dotted paths are supported by ValueOf
Headers Maps context field names to incoming HTTP header names
Constants Static string values inserted into the request context
Ip Context key under which the remote IP is stored by the context builder
Masks Comma-separated list of mapped field names eligible for the string masking callback

Json, Body and Fields are present in these configuration structs, but the supplied server middleware implementation does not currently use them to change logging behavior. Do not rely on them without checking the exact version being built.

For request/response body logging, configure the Request and Response field names explicitly. Do not enable body logging indiscriminately for endpoints that handle credentials, access tokens, payment data or other sensitive values.

Context-building middleware

Each framework integration has a BuildContext or BuildContextWithMask helper:

  • middleware.BuildContext / BuildContextWithMask return a standard http.Handler wrapper.
  • GinLogger.BuildContextWithMask returns a Gin handler.
  • EchoLogger.BuildContextWithMask returns an Echo handler.

These helpers can add remote IP, configured constants, values read from HTTP headers and values extracted from JSON request bodies to the request context. A Map entry maps a context key to a top-level or dotted JSON path. With BuildContextWithMask, selected string fields can be transformed by the supplied func(fieldName, value string) string callback.

Gin example

import (
    "context"

    applog "github.com/core-go/log"
    ginlog "github.com/core-go/log/gin"
    "github.com/gin-gonic/gin"
)

func setupRouter() *gin.Engine {
    router := gin.New()
    config := ginlog.LogConfig{Log: true, Request: "request", Response: "response", ResponseStatus: "status"}
    logInfo := func(ctx context.Context, message string, fields map[string]interface{}) {
        applog.InfoWithFields(ctx, message, fields)
    }
    logger := ginlog.NewGinLogger(config, logInfo, ginlog.NewLogger(), nil)
    router.Use(logger.Logger())
    return router
}

Echo v4 example

import (
    "context"

    applog "github.com/core-go/log"
    echolog "github.com/core-go/log/echo"
    "github.com/labstack/echo/v4"
)

func setupEcho() *echo.Echo {
    e := echo.New()
    config := echolog.LogConfig{Log: true, Request: "request", Response: "response", ResponseStatus: "status"}
    logInfo := func(ctx context.Context, message string, fields map[string]interface{}) {
        applog.InfoWithFields(ctx, message, fields)
    }
    logger := echolog.NewEchoLogger(config, logInfo, echolog.NewLogger(), nil)
    e.Use(logger.Logger)
    return e
}

For Echo v3, use github.com/core-go/log/echo/v3 and the matching older Echo module. Do not mix the v3 adapter with Echo v4 types.

Panic recovery

middleware.Recover(log) wraps a standard HTTP handler, recovers panics, calls the supplied logging callback and writes a JSON 500 Internal Server Error response. GetError converts the recovered value to a string. PanicHandler is a test/helper handler that deliberately panics; it is not an application recovery middleware.

Outbound HTTP client

The client package builds and uses net/http clients and provides JSON-oriented request helpers.

Creating a client

The source exposes two related configuration shapes:

  • Conf: transport/TLS settings (Insecure, Timeout, CertFile, KeyFile, PEMFile).
  • Config: those transport settings plus Url, Username and Password.
  • ClientConfig: Endpoint Config plus optional Log *LogConfig.
  • ClientConf: Config Conf, Endpoint Endpoint and optional Log *LogConfig.

NewClient creates an *http.Client. InitializeClient and InitClient additionally build Basic authentication headers and normalized log settings. InitializeParams and InitParams return a Params value containing the client, base URL, headers, log config and optional error/info logging callbacks.

SetClient sets a package-global default client. DoJSONWithClient and DoWithClient use that global client when their client argument is nil.

Sending and decoding JSON

The package provides low-level DoJSON, AddHeaderAndDoJSON and method helpers (DoGet, DoDelete, DoPost, DoPut, DoPatch) that return *http.Response.

Higher-level helpers include GetDecoder, DeleteDecoder, PostDecoder, PutDecoder, PatchDecoder and their WithHeader variants. Get, Delete, Post, Put and Patch decode a response into a caller-provided result value. DoJSONAndDecode accepts an errorStatus threshold; a negative threshold disables the status-code threshold check, while responses at or above a non-negative threshold are returned as HttpError values.

Marshal passes through []byte and string inputs and JSON-marshals other values. The request helpers add Content-Type: application/json.

HTTP logging and errors

DoWithClient, DoAndBuildDecoder and DoAndLog accept optional callbacks in this order:

  1. error logger: func(context.Context, string, map[string]interface{})
  2. info logger: func(context.Context, string, map[string]interface{})

LogConfig controls whether successful requests are logged and the field names for request, response, status, size, duration and error. Separate controls whether eligible request bodies are logged in a distinct event. HttpError stores status, root error, URL, request/response text, duration and additional error metadata. Use IsHttpError to check for the concrete type and MakeMap to convert its details to a map.

HTTP log publisher

The /http package has a Publisher that POSTs log bytes to an HTTP endpoint as JSON:

import (
    "context"
    "net/http"

    loghttp "github.com/core-go/log/http"
)

func publish(client *http.Client, endpoint string, payload []byte) error {
    publisher := loghttp.NewPublisher(client, endpoint, nil, false)
    return publisher.Publish(context.Background(), payload)
}

NewPublisher accepts an HTTP client, URL, optional error callback, a Goroutines flag and optional retry delays. When Goroutines is true, Publish starts the POST in a goroutine and returns immediately; otherwise it waits for the attempt/retries to complete. Retry delays are time.Duration values. In the supplied implementation the response status specially handled by this publisher is 503 Service Unavailable.

Google Cloud Pub/Sub

The /pubsub package wraps the Google Cloud Pub/Sub client.

Creating a client

  • NewPubSubClient(ctx, credentials, projectID) uses JSON credentials when supplied, otherwise it lets the Google client use its default credential resolution.
  • NewPubSubClientWithFile(ctx, projectID, keyFilename) uses a credentials file when the file exists; otherwise it falls back to default credentials.
  • NewPubSubClientWithRetries(ctx, credentials, retryDelays, projectID) retries client construction after failures.

ClientConfig contains ProjectId, Credentials and KeyFilename. PublisherConfig combines a client config, topic ID, topic settings and retry settings.

Publishing

NewPublisher creates a topic publisher and accepts an optional converter with signature func(context.Context, []byte) ([]byte, error). Publisher.Publish applies that converter, attaches optional message attributes and waits for the Pub/Sub publish result.

NewPublisherByConfig creates the client from PublisherConfig, using retry settings when Retry1 is positive. TopicConfig exposes delay/count/byte thresholds and the number of publishing goroutines.

Health check and permissions

NewHealthChecker checks either publish or subscribe permission for a topic/subscription. NewPubHealthChecker is a publish-permission convenience constructor. The default timeout is four seconds; an optional timeout overrides it. Check calls the Pub/Sub IAM TestPermissions API, and Build adds an error entry to a returned data map when a check fails.

CheckPermission logs a permission check for a topic IAM handle. The NewPublisher constructor invokes it, but the helper logs the outcome rather than returning a permission error to the caller.

Utility packages

strings

  • Mask(s, start, end, mask) preserves the requested leading and trailing portions and replaces the middle with repeated mask text.
  • MaskMargin(s, start, end, mask) preserves the middle portion and replaces the margins.

The indices are byte-based Go string indices, not Unicode grapheme positions.

convert

  • ToCamel(s) converts underscore-separated text to camel case.
  • ToCamelCase(map[string]string) applies that conversion to each map key and preserves its associated value.

Root package and /zap file helpers

GenerateFileNameLog replaces a ${...} segment with time.Now().Format(...), then ensures the parent directory exists. For example, a path template can include ${2006-01-02} using Go's reference-time layout syntax. CreatePath creates the parent directory when it does not exist.

/zap size helpers

SizeOfFile.GetByteSize parses integer sizes in B, KB, MB or GB. The package defines binary byte constants (KiB, MiB, GiB, etc.); the parser's supported suffixes are the four listed above.

Configuration reference

A typical application using the root logger and HTTP middleware can keep the configuration focused on the fields it actually needs:

log:
  level: info
  timestamp_format: "2006-01-02T15:04:05.000Z0700"

http_log:
  log: true
  build: true
  uri: uri
  method: method
  remote_ip: remoteIp
  request: request
  response: response
  status: status
  duration: duration
  size: size

These are examples of the struct tags and field names in the source, not a single library-wide configuration loader. The library defines structs; the application is responsible for loading YAML/JSON/environment configuration and passing the resulting values to the constructors.

Implementation notes and cautions

The following points are visible in the supplied source and are relevant when adopting or extending the library:

  1. No module metadata or tests in the supplied archive. There is no go.mod or *_test.go file in the archive. Confirm versions and run tests in the actual module/repository before relying on a specific build claim.
  2. Global logger state. The root Logrus package and /zap package each keep package-level logger/config state. Initialization is process-wide for each package; avoid assuming per-request or independently configured instances.
  3. Context values are expected under string keys. The Logrus and Zap adapters use configured string keys with ctx.Value. Callers should account for this implementation detail when adding context metadata.
  4. DebugMsg aliases currently call Info. In both the root Logrus package and /zap, DebugMsg delegates to the info-level method. Use Debug directly when a debug-level event is required.
  5. Request/response body capture can expose secrets. The HTTP middleware and outbound client can include body content in logs. Use explicit allowlists and masking, and avoid recording credentials, tokens, session identifiers or sensitive personal data.
  6. Mask callbacks operate on decoded JSON objects. The masking logger parses body text into map[string]interface{} before invoking callbacks. It does not guarantee sanitization of non-JSON, nested non-object, binary or other payload formats.
  7. Certificate-based TLS helper needs review before production use. GetTLSClientConfig sets InsecureSkipVerify: true in the supplied source. Its certificate path therefore does not perform normal server certificate verification by default. Do not treat it as a secure TLS default; review and correct the verification policy for the deployment.
  8. NewTLSClient timeout branch appears inverted. In the supplied source, a non-nil timeout is not assigned to the returned http.Client, while the nil branch dereferences the nil pointer. Review/fix this function before using it with certificate files.
  9. Some declared middleware config fields are not currently consumed. In the supplied server middleware code, Json, Body and the parsed Fields setting do not currently alter the logger behavior. Verify current source before relying on these fields.
  10. Asynchronous logging is not an acknowledgment mechanism. Several middleware formatters launch sending/logging callbacks in goroutines. Their completion and errors are not returned to the request handler. Ensure the callback itself is concurrency-safe and use a durable queue when delivery guarantees matter.
  11. Pub/Sub permission checks are informational in publisher setup. The CheckPermission helper logs the result; it does not return an error that prevents publisher construction.
  12. Fatal and panic methods have control-flow effects. Logrus and Zap fatal/panic methods retain their underlying logger semantics. Use error-level logging for failures that should not terminate or panic the process.

These are implementation observations, not recommendations to change behavior without compatibility review. An application should verify the exact library revision it vendors before relying on any detail above.

License

MIT

log

A typical micro service

  • When you zoom one micro service, the flow is as below, and you can see "log (zap, logrus)" and "middleware" in the full picture: A typical micro service

Content for logging

Request

Features

  • Log Request Method and URL: Log the HTTP method (GET, POST, etc.) and the requested URL.
  • Log Request Headers: Option to log request headers for debugging purposes.
  • Log Request Body: Option to log the request body (with configurable size limits to avoid logging large payloads).

Benefits

  • Debugging: Helps in tracing and debugging issues by providing complete information about incoming requests.
  • Monitoring: Provides visibility into the types of requests being received.

Response

Features

  • Log Response Status Code: Log the HTTP status code of the response.
  • Log Response Headers: Option to log response headers.
  • Log Response Body: Option to log the response body (with configurable size limits to avoid logging large payloads).

Benefits

  • Debugging: Assists in diagnosing issues by providing complete information about the responses sent by the server.
  • Auditing: Helps in auditing and reviewing server responses for compliance and monitoring purposes.

Response Time

Features

  • Log Response Time: Calculate and log the time taken to process each request.

Benefits

  • Performance Monitoring: Helps in identifying slow requests and performance bottlenecks.
  • Optimization: Provides data to optimize and improve server response times.

Response Size

Features

  • Log Response Size: Log the size of the response payload in bytes.

Benefits

  • Bandwidth Monitoring: Helps in monitoring and managing bandwidth usage.
  • Optimization: Provides insights into the response sizes to optimize payloads and improve performance.

Features

Middleware Integration

Features

Benefits

  • Ease of Use: Simplifies the integration of logging into existing web applications.
  • Consistency: Ensures consistent logging across different parts of the application.

Logging Libraries Integration

  • Do not depend on any logging libraries.
  • Already supported to integrate with zap, logrus
  • Can be integrated with any logging library.

Enable/Disable Logging

Features

  • Enable/Disable Logging: Allow users to turn on or off logging for requests, responses, headers, and bodies independently.
  • Logging Levels: Support different logging levels (e.g., INFO, DEBUG, ERROR) to control the verbosity of logs.

Benefits

  • Flexibility: Provides users with the flexibility to configure logging based on their needs and environment.
  • Efficiency: Reduces overhead by allowing selective logging, especially in production environments.

Asynchronous Logging

Features

  • Non-Blocking Logs: Implement asynchronous logging to ensure that logging does not block request processing.
  • Log Buffering: Use buffering to improve logging performance and reduce latency.

Benefits:

  • Performance: Improves the overall performance of the application by reducing logging overhead.
  • Scalability: Allows the application to handle high-throughput logging without performance degradation.

Sensitive Data Encryption

Features

Benefits:

  • Security: Protects sensitive information from being exposed in logs.
  • Compliance: Helps meet security and compliance requirements by safeguarding sensitive data.
  • Ease of Use: Simplifies the integration of encryption/masking into any existing applications.
  • Consistency: Ensures that sensitive data is consistently encrypted or masked across all logged requests and responses

Use Cases of sensitive data masking/encrypting

Financial Transactions

  • Benefit: Encrypting sensitive financial data, such as credit card numbers and transaction details, helps comply with PCI-DSS standards and secures financial transactions from exposure in logs.

Healthcare

  • Benefit: Encrypting patient data such as medical records and health information in logs ensures compliance with HIPAA regulations and protects patient privacy.

E-commerce

  • Benefit: Protecting customer information, such as addresses and payment details, enhances customer trust and protects the e-commerce platform from potential data breaches.

Benefits to Developers

Enhanced Debugging

  • Provides detailed logs for requests and responses, aiding in troubleshooting and debugging issues.

Performance Monitoring

  • Logs response times and sizes, allowing developers to monitor and optimize application performance.

Flexibility

  • Configurable logging settings enable developers to tailor the logging behavior to their needs.

Ease of Integration

  • Middleware function can be easily integrated into existing web frameworks, simplifying the setup process.

Improved Maintainability

  • Centralized logging logic ensures consistency and makes the codebase easier to maintain.

Security:

  • Encrypt or mask sensitive data in logs, reducing the risk of data exposure and meeting compliance requirements.

Conclusion

By implementing these features, you provide a comprehensive logging solution that enhances the visibility, performance, and maintainability of any GO applications.

Installation

Please make sure to initialize a Go module before installing core-go/log:

go get -u github.com/core-go/log

Import:

import "github.com/core-go/log"

Summary of middleware log tracing

log tracing at middleware

middleware log for

  • http
  • echo
  • gin
Support to turn on, turn off
  • request
  • response
  • duration
  • http response status code
  • response content length
Support to mask or encrypt fields
  • support to mask or encrypt fields, such as mobileNumber, creditCardNumber
  • useful for Financial Products (to comply with PCI-DSS standards) and Healthcare (to comply with HIPAA regulations)

Appendix

Microservice Architect

Microservice Architect

Cross-cutting concerns

  • "log" in the full picture of cross-cutting concerns cross-cutting concerns

About

No description or website provided.

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages