github.com/mongodb/grip@v0.0.0-20240213223901-f906268d82b9/message/conditional.go (about) 1 package message 2 3 import ( 4 "github.com/mongodb/grip/level" 5 ) 6 7 type condComposer struct { 8 cond bool 9 msg Composer 10 } 11 12 // When returns a conditional message that is only logged if the 13 // condition is bool. Converts the second argument to a composer, if 14 // needed, using the same rules that the logging methods use. 15 func When(cond bool, m interface{}) Composer { 16 return &condComposer{cond: cond, msg: ConvertToComposer(level.Priority(0), m)} 17 } 18 19 // Whenf returns a conditional message that is only logged if the 20 // condition is bool, and creates a sprintf-style message, which will 21 // itself only log if the base expression is not the empty string. 22 func Whenf(cond bool, m string, args ...interface{}) Composer { 23 return &condComposer{cond: cond, msg: NewFormatted(m, args...)} 24 } 25 26 // Whenln returns a conditional message that is only logged if the 27 // condition is bool, and creates a sprintf-style message, which will 28 // itself only log if the base expression is not the empty string. 29 func Whenln(cond bool, args ...interface{}) Composer { 30 return &condComposer{cond: cond, msg: NewLine(args...)} 31 } 32 33 // WhenMsg returns a conditional message that is only logged if the 34 // condition is bool, and creates a string message that will only log 35 // when the message content is not the empty string. Use this for a 36 // more strongly-typed conditional logging message. 37 func WhenMsg(cond bool, m string) Composer { 38 return &condComposer{cond: cond, msg: NewString(m)} 39 } 40 41 func (c *condComposer) String() string { return c.msg.String() } 42 func (c *condComposer) Raw() interface{} { return c.msg.Raw() } 43 func (c *condComposer) Priority() level.Priority { return c.msg.Priority() } 44 func (c *condComposer) SetPriority(p level.Priority) error { return c.msg.SetPriority(p) } 45 func (c *condComposer) Annotate(k string, v interface{}) error { return c.msg.Annotate(k, v) } 46 func (c *condComposer) Loggable() bool { 47 if c.cond { 48 return c.msg.Loggable() 49 } 50 51 return false 52 }