Rediseñado los errores en los componentes para establecerlos directamente como ErrCode

master
DEV 2 years ago
parent 164de3cfd9
commit 8c28934b40

@ -14,17 +14,24 @@ func Print (err error) {
}
func Append (entry *hecate.Entry) error {
fmt.Printf("%#v\n\n",entry)
return nil
}
func main() {
l := hecate.NewManager("Main",hecate.LevelAll)
l := hecate.NewLoggerManager("Main",hecate.LevelAll)
l.AddCore(hecate.NewLoggerCore("MiLogger",hecate.LevelAll,hecate.LoggerCoreWithAppender(hecate.AppendEntryFnc(Append))))
l.Start(true)
l.Warn("Esto es un mensage")
l.Error("Esto es un mensage",errs.ErrCode("UnError"))
l.Fatal("Fatalidad",errs.NewErrPanic(errs.ErrCode("unca cauisa")))
_,er := l.AddScope("Root")
Print(er)
_,er = l.AddScope("Root.main")
Print(er)
_,er = l.AddScope("Root")
Print(er)

@ -23,22 +23,91 @@
package astrings
import "sync"
import (
"strings"
"sync"
)
const(
UpperTransformer string = "upper"
LowerTransformer string = "lower"
TrimTransformer string = "trim"
TitleTransformer string = "title"
CamelTransformer string = "camel"
LCamelTransformer string = "l-camel"
SnakeTransformer string = "snake"
USnakeTransformer string = "u-snake"
KebabTransformer string = "kebab"
UKebabTransformer string = "u-kebab"
)
var (
G = struct {
ErrTransformerNotFound ErrAStrings
} {
ErrTransformerNotFound: ErrAStrings("transformer-not-found"),
}
uppercaseAcronym sync.Map
g = struct {
sync.RWMutex
uppercaseAcronym map[string]string
} {
iniTransformers sync.Once
transformers map[string]Transformer
}{
}
)
func AddAcronym (key, val string) {
G.uppercaseAcronym.Store(key, val)
func AddAcronym (key, value string) {
g.Lock()
g.uppercaseAcronym[key] = value
g.Unlock()
}
func GetAcronym (key string) (string, bool) {
g.RLock()
v,h := g.uppercaseAcronym[key]
g.RUnlock()
return v,h
}
func GetTransformer (name string) Transformer {
g.iniTransformers.Do(initTransformers)
g.RLock()
t,_ := g.transformers[name]
g.RUnlock()
return t
}
func AddTransformer (name string, transformer Transformer) {
g.iniTransformers.Do(initTransformers)
if transformer != nil {
g.Lock()
g.transformers[name]=transformer
g.Unlock()
}
}
func initTransformers () {
g.transformers = map[string]Transformer {
UpperTransformer : TransformFnc(strings.ToUpper),
LowerTransformer : TransformFnc(strings.ToLower),
TrimTransformer : TransformFnc(strings.TrimSpace),
TitleTransformer : TransformFnc(strings.ToTitle),
CamelTransformer : TransformFnc(ToCamel),
LCamelTransformer: TransformFnc(ToLowerCamel),
SnakeTransformer : TransformFnc(ToSnake),
USnakeTransformer: TransformFnc(ToUSnake),
KebabTransformer : TransformFnc(ToKebab),
UKebabTransformer: TransformFnc(ToUKebab),
}
}

@ -36,9 +36,9 @@ func toCamelInitCase(s string, initCase bool) string {
if s == "" {
return s
}
a, hasAcronym := G.uppercaseAcronym.Load(s)
a, hasAcronym := GetAcronym(s)
if hasAcronym {
s = a.(string)
s = a
}
n := strings.Builder{}

@ -0,0 +1,51 @@
// ------------------------------------------------------------------------
// Project active2
// Active Thing (activething.com) git.activething.com/go
//
// File name err_astrings.go
// Created by DEV
// Modified 26/04/2024
//
// Copyright 2024 activething.com
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
package astrings
import "errs/collects"
type (
// ErrAStrings no puede heredar directamente de Errs.Code
// ya que es utilizada por fjson y ftext lo que crea
// un ciclo de importaciones
//
ErrAStrings string
)
func (e ErrAStrings) Error() string {
return string(e) }
func (e ErrAStrings) Code () string {
return string(e) }
func (e ErrAStrings) Collect (c collects.Collector) {
c.AddFieldString(collects.FieldNameCode,string(e)) }

@ -35,12 +35,12 @@ func ToSnake(s string) string {
func ToSnakeWithIgnore(s string, ignore string) string {
return ToScreamingDelimited(s, '_', ignore, false)
return ToUDelimited(s, '_', ignore, false)
}
// ToScreamingSnake converts a string to SCREAMING_SNAKE_CASE
func ToScreamingSnake(s string) string {
return ToScreamingDelimited(s, '_', "", true)
// ToUSnake converts a string to SCREAMING_SNAKE_CASE
func ToUSnake(s string) string {
return ToUDelimited(s, '_', "", true)
}
// ToKebab converts a string to kebab-case
@ -48,9 +48,9 @@ func ToKebab(s string) string {
return ToDelimited(s, '-')
}
// ToScreamingKebab converts a string to SCREAMING-KEBAB-CASE
func ToScreamingKebab(s string) string {
return ToScreamingDelimited(s, '-', "", true)
// ToUKebab converts a string to SCREAMING-KEBAB-CASE
func ToUKebab(s string) string {
return ToUDelimited(s, '-', "", true)
}
@ -58,24 +58,24 @@ func ToScreamingKebab(s string) string {
// ToDelimited converts a string to delimited.snake.case
// (in this case `delimiter = '.'`)
func ToDelimited(s string, delimiter uint8) string {
return ToScreamingDelimited(s, delimiter, "", false)
return ToUDelimited(s, delimiter, "", false)
}
// ToScreamingDelimited converts a string to SCREAMING.DELIMITED.SNAKE.CASE
// (in this case `delimiter = '.'; screaming = true`)
// ToUDelimited converts a string to SCREAMING.DELIMITED.SNAKE.CASE
// (in this case `delimiter = '.'; upper = true`)
// or delimited.snake.case
// (in this case `delimiter = '.'; screaming = false`)
func ToScreamingDelimited(s string, delimiter uint8, ignore string, screaming bool) string {
func ToUDelimited(s string, delimiter uint8, ignore string, upper bool) string {
s = strings.TrimSpace(s)
n := strings.Builder{}
n.Grow(len(s) + 2) // nominal 2 bytes of extra space for inserted delimiters
for i, v := range []byte(s) {
vIsCap := v >= 'A' && v <= 'Z'
vIsLow := v >= 'a' && v <= 'z'
if vIsLow && screaming {
if vIsLow && upper {
v += 'A'
v -= 'a'
} else if vIsCap && !screaming {
} else if vIsCap && !upper {
v += 'a'
v -= 'A'
}

@ -23,8 +23,7 @@
package astrings
import "errs/errf"
type (
@ -33,6 +32,17 @@ type (
)
func MakeTransformers (names ...string) Transformers {
var l Transformers
for _,name := range names {
if t := GetTransformer(name); t != nil {
l = append(l, t)
continue
}
panic(errf.NewFieldString(G.ErrTransformerNotFound,"transformer",name))
}
return l
}
func (a Transformers) Transform (value string) string {
if len(a) == 0 {

@ -46,7 +46,7 @@ type (
// Implements -> Tokenizer
//
ATokenizer struct {
aTokenizerChars
aTokenizerChars
MinLenToken int
MaxLenToken int

@ -42,6 +42,8 @@ func NewGQueue [T any](safe bool) *GQueue[T] {
var lc syncs.LockerRW
if safe {
lc = &sync.RWMutex{}
} else {
lc = syncs.NopLocker{}
}
return &GQueue[T]{ locker : lc }
}

@ -24,6 +24,7 @@
package hecate
import (
"atypes/astrings"
"bins/tokens"
"errs"
"mems"
@ -56,14 +57,6 @@ const (
filterScopeName string = "scope"
)
const (
fmtMsgLogLogErr = "Error logging logger %s"
fmtMsgLogStartErr = "Error starting logger %s"
fmtMsgLogStopErr = "Error stopping logger %s"
fmtMsgLogFlushErr = "Error flushing logger %s"
)
var (
@ -77,7 +70,8 @@ var (
ErrLoggerStarted errs.ErrCode
ErrLoggerNotStarted errs.ErrCode
ScopeSep byte
ScopeSep byte
ScopeNameTransforms astrings.Transformers
FmtMsgLogLogErr string
FmtMsgLogStartErr string
@ -95,6 +89,7 @@ var (
ErrLoggerNotStarted : errs.ErrCode("logger-not-started"),
ScopeSep : '.',
ScopeNameTransforms : astrings.MakeTransformers("lower"),
FmtMsgLogLogErr : "Error logging logger %s",
FmtMsgLogStartErr : "Error starting logger %s",
@ -110,12 +105,16 @@ var (
tokenizer tokens.ATokenizer
scopeSepStr string
}{
idGen : *syncs.NewAUInt64(uint64(time.Now().Unix())),
bufferPool: *mems.NewPool(),
tokenizer : *tokens.NewATokenizer(),
entryPool : *pools.NewGPool[Entry](pools.WithNew(newEntry)),
entryPool : *pools.NewGPool[Entry](
pools.WithNew(newEntry),
),
tokenizer : *tokens.NewATokenizer(func (c *tokens.ATokenizer) {
c.TokenSep = '.'
}),
scopeSepStr : ".",
}
)

@ -31,12 +31,12 @@ type (
Name () string
Level() Level
Fatal (message string, err error, options ...EntryFnc)
Error (message string, err error, options ...EntryFnc)
Warn (message string, options ...EntryFnc)
Info (message string, options ...EntryFnc)
Debug (message string, options ...EntryFnc)
Data (message string, data any, options ...EntryFnc)
Fatal(message string, err error, options ...EntryFnc)
Error(message string, err error, options ...EntryFnc)
Warn (message string, options ...EntryFnc)
Info (message string, options ...EntryFnc)
Debug(message string, options ...EntryFnc)
Data (message string, data any, options ...EntryFnc)
}
)

@ -110,7 +110,7 @@ func (l *LoggerCore) SetLevel (level Level) {
func (l *LoggerCore) Start () error {
l.Lock()
er := l.Start()
er := l.start()
l.Unlock()
return er
}
@ -124,7 +124,7 @@ func (l *LoggerCore) start () error {
l.handleError(er,nil)
return er
}
l.state = StateCreated
l.state = StateStarted
return nil
}
@ -251,6 +251,8 @@ func (l *LoggerCore) handleError (err error, entry *Entry) {
return
}
l.errors = l.errors.Append(err)
if l.onErrorFn != nil {
l.onErrorFn(l, entry, err)
}

@ -33,7 +33,7 @@ import (
type (
Manager struct {
LoggerManager struct {
sync.RWMutex
EntryFilters
EntryExtenders
@ -49,22 +49,22 @@ type (
count int
logErrors bool
errors errs.ErrorList
onErrorFn ManagerErrorFnc
onFatalFn ManagerEntryFnc
errors errs.ErrorList
onErrorFn LoggerManagerErrorFnc
onFatalFn LoggerManagerEntryFnc
}
ManagerFnc func(manager *Manager)
LoggerManagerFnc func(manager *LoggerManager)
ManagerErrorFnc func(manager *Manager, err error)
LoggerManagerErrorFnc func(manager *LoggerManager, err error)
ManagerEntryFnc func(manager *Manager, entry *Entry)
LoggerManagerEntryFnc func(manager *LoggerManager, entry *Entry)
)
func NewManager(name string, level Level, options ...ManagerFnc) *Manager {
l := &Manager{
func NewLoggerManager(name string, level Level, options ...LoggerManagerFnc) *LoggerManager {
l := &LoggerManager{
EntryFilters: *NewEntryFilters(),
level : level,
state : StateCreated,
@ -79,23 +79,23 @@ func NewManager(name string, level Level, options ...ManagerFnc) *Manager {
func (l *Manager) Name() string {
func (l *LoggerManager) Name() string {
return l.name }
func (l *Manager) Level() Level {
func (l *LoggerManager) Level() Level {
l.RLock()
lv := l.level
l.RUnlock()
return lv
}
func (l *Manager) SetLevel (level Level) {
func (l *LoggerManager) SetLevel (level Level) {
l.Lock()
l.level = level
l.Unlock()
}
func (l *Manager) State () State {
func (l *LoggerManager) State () State {
l.RLock()
s := l.state
l.RUnlock()
@ -103,7 +103,7 @@ func (l *Manager) State () State {
}
func (l *Manager) Errors () errs.ErrorList {
func (l *LoggerManager) Errors () errs.ErrorList {
l.RLock()
ls := l.errors
l.RUnlock()
@ -112,7 +112,7 @@ func (l *Manager) Errors () errs.ErrorList {
}
func (l *Manager) Start (all bool) error {
func (l *LoggerManager) Start (all bool) error {
l.Lock()
if l.state == StateStarted {
l.Unlock()
@ -132,7 +132,7 @@ func (l *Manager) Start (all bool) error {
}
func (l *Manager) Stop (all bool) error {
func (l *LoggerManager) Stop (all bool) error {
l.Lock()
if l.state != StateStarted {
l.Unlock()
@ -150,14 +150,14 @@ func (l *Manager) Stop (all bool) error {
}
func (l *Manager) Flush () error {
func (l *LoggerManager) Flush () error {
l.Lock()
return l.doCores(nil,func(c *LoggerCore,_ *Entry) error { return c.Flush() }, G.FmtMsgLogFlushErr,true)
}
func (l *Manager) GetCore (name string) *LoggerCore {
func (l *LoggerManager) GetCore (name string) *LoggerCore {
l.RLock()
var co *LoggerCore
if p := l.findCore(name); p != -1 {
@ -167,7 +167,7 @@ func (l *Manager) GetCore (name string) *LoggerCore {
return co
}
func (l *Manager) AddCore (core *LoggerCore) error {
func (l *LoggerManager) AddCore (core *LoggerCore) error {
l.Lock()
if p := l.findCore(core.name); p != -1 {
l.Unlock()
@ -182,7 +182,7 @@ func (l *Manager) AddCore (core *LoggerCore) error {
return er
}
func (l *Manager) DelCore (name string) error {
func (l *LoggerManager) DelCore (name string) error {
l.Lock()
p := l.findCore(name)
if p != -1 {
@ -198,8 +198,9 @@ func (l *Manager) DelCore (name string) error {
func (l *Manager) GetScope(name string) *LoggerScope {
ns := strings.Split(strings.ToLower(name),g.scopeSepStr)
func (l *LoggerManager) GetScope(name string) *LoggerScope {
ns := strings.Split(G.ScopeNameTransforms.Transform(name),g.scopeSepStr)
l.RLock()
sc := l.scopes.getScope(ns[0])
if sc != nil && len(ns) > 1 {
@ -209,9 +210,10 @@ func (l *Manager) GetScope(name string) *LoggerScope {
return sc
}
func (l *Manager) AddScope(name string, options ...LoggerScopeFnc) (*LoggerScope,error) {
nm := strings.ToLower(name)
func (l *LoggerManager) AddScope(name string, options ...LoggerScopeFnc) (*LoggerScope,error) {
nm := G.ScopeNameTransforms.Transform(name)
ns := strings.Split(nm,g.scopeSepStr)
l.Lock()
sc := l.scopes.getScope(ns[0])
if sc == nil {
@ -232,31 +234,31 @@ func (l *Manager) AddScope(name string, options ...LoggerScopeFnc) (*LoggerScope
func (l *Manager) Fatal (msg string, err error, ops ...EntryFnc){
func (l *LoggerManager) Fatal (msg string, err error, ops ...EntryFnc){
l.log(LevelFatal,msg,err,ops) }
func (l *Manager) Error (msg string, err error, ops ...EntryFnc){
func (l *LoggerManager) Error (msg string, err error, ops ...EntryFnc){
l.log(LevelError,msg,err,ops) }
func (l *Manager) Warn (msg string, ops ...EntryFnc){
func (l *LoggerManager) Warn (msg string, ops ...EntryFnc){
l.log(LevelWarn,msg,nil,ops) }
func (l *Manager) Info (msg string, ops ...EntryFnc){
func (l *LoggerManager) Info (msg string, ops ...EntryFnc){
l.log(LevelInfo,msg,nil,ops) }
func (l *Manager) Debug (msg string, ops ...EntryFnc){
func (l *LoggerManager) Debug (msg string, ops ...EntryFnc){
l.log(LevelDebug,msg,nil,ops) }
func (l *Manager) Data (msg string, data any, ops ...EntryFnc){
func (l *LoggerManager) Data (msg string, data any, ops ...EntryFnc){
l.log(LevelData,msg,nil,[]EntryFnc{EntryWithData(data,ops...)}) }
func (l *Manager) Log (entry *Entry) error {
func (l *LoggerManager) Log (entry *Entry) error {
if entry == nil {
return nil
}
@ -279,7 +281,7 @@ func (l *Manager) Log (entry *Entry) error {
}
func (l *Manager) log (level Level, msg string, err error,options []EntryFnc) {
func (l *LoggerManager) log (level Level, msg string, err error,options []EntryFnc) {
l.Lock()
if l.state != StateStarted || !l.level.Has(level){
l.Unlock()
@ -297,7 +299,7 @@ func (l *Manager) log (level Level, msg string, err error,options []EntryFnc) {
}
func (l *Manager) handleError (err error, entry *Entry) {
func (l *LoggerManager) handleError (err error, entry *Entry) {
if err == nil {
return
}
@ -314,7 +316,7 @@ func (l *Manager) handleError (err error, entry *Entry) {
}
func (l *Manager) enqueue() {
func (l *LoggerManager) enqueue() {
for en := l.queue.Pop(); en != nil; {
_ = l.doCores(en,func(c *LoggerCore, e *Entry) error { return c.Append(e) },G.FmtMsgLogLogErr,true)
ReleaseEntry(en)
@ -322,7 +324,7 @@ func (l *Manager) enqueue() {
}
func (l *Manager) doCores (entry *Entry, doFn func(c *LoggerCore, e *Entry) error, msg string, unlock bool) error {
func (l *LoggerManager) doCores (entry *Entry, doFn func(c *LoggerCore, e *Entry) error, msg string, unlock bool) error {
var el errs.ErrorList
for _,co := range l.cores {
if er := doFn(co,entry); er != nil {
@ -346,7 +348,7 @@ func (l *Manager) doCores (entry *Entry, doFn func(c *LoggerCore, e *Entry) erro
return nil
}
func (l *Manager) findCore(name string) int {
func (l *LoggerManager) findCore(name string) int {
for i :=0; i < len(l.cores); i++ {
if l.cores[i].name == name {
return i
@ -356,3 +358,27 @@ func (l *Manager) findCore(name string) int {
}
func LoggerManagerWithFilters (configFilters EntryFiltersFnc) LoggerManagerFnc {
return func(a *LoggerManager) {
configFilters(&a.EntryFilters) } }
func LoggerManagerWithOnFatal (onFatal LoggerManagerEntryFnc) LoggerManagerFnc {
return func(a *LoggerManager) {
a.onFatalFn = onFatal } }
func LoggerManagerWithOnError (onError LoggerManagerErrorFnc) LoggerManagerFnc {
return func(a *LoggerManager) {
a.onErrorFn = onError } }
func LoggerManagerWithExtender (extender ...EntryExtender) LoggerManagerFnc {
return func(a *LoggerManager) {
a.EntryExtenders = append(a.EntryExtenders,extender...) } }
func LoggerManagerWithErrors (extender ...EntryExtender) LoggerManagerFnc {
return func(a *LoggerManager) {
} }
Loading…
Cancel
Save

Powered by TurnKey Linux.