Skip to content

Instantly share code, notes, and snippets.

@vadzappa
vadzappa / logger.go
Created April 9, 2020 09:40
Sample logger
package logger
import (
"log"
)
func Log(level, message string, args ...interface{}) {
params := append([]interface{}{level + ": ", message + " "}, args...)
log.Print(params...)
package controller
import (
"blodpost/logger"
"blodpost/protocol"
"github.com/pkg/errors"
"math/rand"
)
func Process(company *protocol.Company) error {
package main
import (
"blodpost/controller"
"blodpost/protocol"
)
func main() {
_ = controller.Process(&protocol.Company{
Id: 11,
syntax = "proto3";
import "options.proto";
package protocol;
option go_package = ".;protocol";
message Title {
int64 id = 1 [(protocol.options).logField = "profession_id"];
func Log(level, message string, args ...interface{}) {
params := append([]interface{}{level + ": ", message + " "}, sanitize(args...)...)
log.Print(params...)
}
syntax = "proto3";
import "google/protobuf/descriptor.proto";
package protocol;
option go_package = ".;protocol";
message FieldOptions {
string logField = 1;
func sanitize(args ...interface{}) []interface{} {
res := make([]interface{}, 0, len(args))
for _, v := range args {
switch a := v.(type) {
case protoreflect.ProtoMessage:
res = append(res, sanitizeProtoMessage(a))
default:
res = append(res, a)
}
func sanitizeProtoMessage(m protoreflect.ProtoMessage, parentPrefixes ...string) map[string]interface{} {
result := make(map[string]interface{})
reflect := m.ProtoReflect()
reflect.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
if !v.IsValid() {
return true
}
if fd.IsList() || fd.IsMap() {
return true
func extractLogField(fd protoreflect.FieldDescriptor, hasPrefix bool) (string, bool) {
// check if there are any options available for the field
opts, ok := fd.Options().(*descriptorpb.FieldOptions)
if !ok || opts == nil {
return "", false
}
// check if protocol.FieldOptions specified for the field
// basically extracting anything from [(protocol.options).logField = "something_here"]
field, ok := proto.GetExtension(opts, protocol.E_Options).(*protocol.FieldOptions)
if !ok || field == nil {
func logFieldName(prefixes []string) string {
filtered := make([]string, 0, len(prefixes))
for _, p := range prefixes {
if p != "" {
filtered = append(filtered, p)
}
}
return strings.Join(filtered, "_")
}