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.
- Capabilities
- Package map
- Installation and dependencies
- Root logger: Logrus
- Zap adapter
- HTTP server request/response logging
- Outbound HTTP client
- HTTP log publisher
- Google Cloud Pub/Sub
- Utility packages
- Configuration reference
- Implementation notes and cautions
| 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 |
| 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.
In a Go module that can resolve the repository, add the library with:
go get github.com/core-go/logThe 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.
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.
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.
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.
The root logger enriches every event with values from the supplied context:
- If
Config.FieldMapis set, the value at that context key is expected to bemap[string]interface{}; each key/value pair is copied into the event. - Each name in
Config.Fieldsis looked up separately. Only non-empty values of typestringare copied. - Duration helpers add elapsed milliseconds under the configured
Durationkey.
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()returns the*logrus.Loggercreated by the most recentInitializecall.IsTraceEnable,IsDebugEnable,IsInfoEnable,IsWarnEnableandIsErrorEnablequery the Logrus package-global logger's level.Key(logger)returns the field-map key mapping when the supplied logger uses*logrus.JSONFormatter; otherwise it returnsnil.FatalandPanicinherit the termination/panic behavior of Logrus. They should not be used as ordinary error-reporting calls.
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:
InitializeandInitializeWithWriterto construct and store the package logger.SetLoggerto install an externally created*zap.Logger.Loggerto retrieve the package logger.- Level helpers such as
Debug,Info,Warn,Error,Fatal,PanicandDPanic, plus formatted and field-map variants. DebugDurationandInfoDurationto record elapsed milliseconds.BuildLogFieldsandAppendFieldsto translate maps/context values into Zap fields.
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.
The server logging implementations share a similar design across three integrations:
middleware: standardnet/httphandlers.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.
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 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-suppliedsendfunction.NewLoggerWithJsonFormat: additionally attempts to decode configured request/response bodies into JSON objects for logging.NewLoggerWithSending: enables JSON sending and accepts an optional mapping for thelevel,timeandmsgkeys.NewMaskLoggerandNewMaskLoggerWithSending: 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.
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.
Each framework integration has a BuildContext or BuildContextWithMask helper:
middleware.BuildContext/BuildContextWithMaskreturn a standardhttp.Handlerwrapper.GinLogger.BuildContextWithMaskreturns a Gin handler.EchoLogger.BuildContextWithMaskreturns 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.
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
}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.
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.
The client package builds and uses net/http clients and provides JSON-oriented request helpers.
The source exposes two related configuration shapes:
Conf: transport/TLS settings (Insecure,Timeout,CertFile,KeyFile,PEMFile).Config: those transport settings plusUrl,UsernameandPassword.ClientConfig:Endpoint Configplus optionalLog *LogConfig.ClientConf:Config Conf,Endpoint Endpointand optionalLog *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.
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.
DoWithClient, DoAndBuildDecoder and DoAndLog accept optional callbacks in this order:
- error logger:
func(context.Context, string, map[string]interface{}) - 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.
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.
The /pubsub package wraps the Google Cloud Pub/Sub 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.
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.
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.
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.
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.
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.
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.
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: sizeThese 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.
The following points are visible in the supplied source and are relevant when adopting or extending the library:
- No module metadata or tests in the supplied archive. There is no
go.modor*_test.gofile in the archive. Confirm versions and run tests in the actual module/repository before relying on a specific build claim. - Global logger state. The root Logrus package and
/zappackage each keep package-level logger/config state. Initialization is process-wide for each package; avoid assuming per-request or independently configured instances. - 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. DebugMsgaliases currently callInfo. In both the root Logrus package and/zap,DebugMsgdelegates to the info-level method. UseDebugdirectly when a debug-level event is required.- 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.
- 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. - Certificate-based TLS helper needs review before production use.
GetTLSClientConfigsetsInsecureSkipVerify: truein 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. NewTLSClienttimeout branch appears inverted. In the supplied source, a non-nil timeout is not assigned to the returnedhttp.Client, while the nil branch dereferences the nil pointer. Review/fix this function before using it with certificate files.- Some declared middleware config fields are not currently consumed. In the supplied server middleware code,
Json,Bodyand the parsedFieldssetting do not currently alter the logger behavior. Verify current source before relying on these fields. - 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.
- Pub/Sub permission checks are informational in publisher setup. The
CheckPermissionhelper logs the result; it does not return an error that prevents publisher construction. - 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.
MIT
-
wrapper of zap
-
wrapper of logrus
-
middleware tracing log for Echo, Gin, or net/http (Gorilla mux, Go-chi)
- useful for Financial Products (to comply with PCI-DSS standards) and Healthcare (to comply with HIPAA regulations)
-
You can refer to middleware-log-tracing at my Linked In for more details.
- When you zoom one micro service, the flow is as below, and you can see "log (zap, logrus)" and "middleware" in the full picture:
- 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).
- Debugging: Helps in tracing and debugging issues by providing complete information about incoming requests.
- Monitoring: Provides visibility into the types of requests being received.
- 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).
- 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.
- Log Response Time: Calculate and log the time taken to process each request.
- Performance Monitoring: Helps in identifying slow requests and performance bottlenecks.
- Optimization: Provides data to optimize and improve server response times.
- Log Response Size: Log the size of the response payload in bytes.
- Bandwidth Monitoring: Helps in monitoring and managing bandwidth usage.
- Optimization: Provides insights into the response sizes to optimize payloads and improve performance.
- Middleware Function: Designed to integrate seamlessly with existing Go libraries: Echo, Gin, or net/http (Gorilla mux, Go-chi).
- Sample for Echo is at go-echo-sql-sample
- Sample for Gin is at go-gin-sql-sample
- Sample for Gorilla mux is at go-sql-sample
- Context Handling: Pass context to handle request-specific data throughout the middleware chain.
- Ease of Use: Simplifies the integration of logging into existing web applications.
- Consistency: Ensures consistent logging across different parts of the application.
- Do not depend on any logging libraries.
- Already supported to integrate with zap, logrus
- Can be integrated with any logging library.
- 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.
- 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.
- 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.
- Performance: Improves the overall performance of the application by reducing logging overhead.
- Scalability: Allows the application to handle high-throughput logging without performance degradation.
- Mask/Encrypt sensitive data in the request and response bodies.
- Sample for Echo is at go-echo-sql-sample
- Sample for Gin is at go-gin-sql-sample
- Sample for Gorilla mux is at go-sql-sample
- Sensitive Data Identification: identify and encrypt specific fields in JSON payloads.
- 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
- 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.
- Benefit: Encrypting patient data such as medical records and health information in logs ensures compliance with HIPAA regulations and protects patient privacy.
- Benefit: Protecting customer information, such as addresses and payment details, enhances customer trust and protects the e-commerce platform from potential data breaches.
- Provides detailed logs for requests and responses, aiding in troubleshooting and debugging issues.
- Logs response times and sizes, allowing developers to monitor and optimize application performance.
- Configurable logging settings enable developers to tailor the logging behavior to their needs.
- Middleware function can be easily integrated into existing web frameworks, simplifying the setup process.
- Centralized logging logic ensures consistency and makes the codebase easier to maintain.
- Encrypt or mask sensitive data in logs, reducing the risk of data exposure and meeting compliance requirements.
By implementing these features, you provide a comprehensive logging solution that enhances the visibility, performance, and maintainability of any GO applications.
Please make sure to initialize a Go module before installing core-go/log:
go get -u github.com/core-go/logImport:
import "github.com/core-go/log"middleware log for
- http
- echo
- gin
- request
- response
- duration
- http response status code
- response content length
- 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)


