ignorableLogger.go (1857B)
1 // Copyright 2020 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package loggers 15 16 import ( 17 "fmt" 18 "strings" 19 ) 20 21 // IgnorableLogger is a logger that ignores certain log statements. 22 type IgnorableLogger interface { 23 Logger 24 Errorsf(statementID, format string, v ...any) 25 Apply(logger Logger) IgnorableLogger 26 } 27 28 type ignorableLogger struct { 29 Logger 30 statements map[string]bool 31 } 32 33 // NewIgnorableLogger wraps the given logger and ignores the log statement IDs given. 34 func NewIgnorableLogger(logger Logger, statements ...string) IgnorableLogger { 35 statementsSet := make(map[string]bool) 36 for _, s := range statements { 37 statementsSet[strings.ToLower(s)] = true 38 } 39 return ignorableLogger{ 40 Logger: logger, 41 statements: statementsSet, 42 } 43 } 44 45 // Errorsf logs statementID as an ERROR if not configured as ignoreable. 46 func (l ignorableLogger) Errorsf(statementID, format string, v ...any) { 47 if l.statements[statementID] { 48 // Ignore. 49 return 50 } 51 ignoreMsg := fmt.Sprintf(` 52 If you feel that this should not be logged as an ERROR, you can ignore it by adding this to your site config: 53 ignoreErrors = [%q]`, statementID) 54 55 format += ignoreMsg 56 57 l.Errorf(format, v...) 58 } 59 60 func (l ignorableLogger) Apply(logger Logger) IgnorableLogger { 61 return ignorableLogger{ 62 Logger: logger, 63 statements: l.statements, 64 } 65 }