Posted to tcl by colin at Tue Aug 28 23:06:17 GMT 2012view raw

  1. # syslog using Udp extension
  2. # Colin McCormack
  3.  
  4. lappend auto_path [pwd]/Udp
  5. package require Udp
  6. package require TclOO
  7. package provide Syslog 1.0
  8.  
  9. oo::class create Syslog {
  10. method timestamp {time} {
  11. # return a timestamp of $time
  12. if {![string is integer -strict $time]} {
  13. set time [clock scan $time -timezone :UTC]
  14. }
  15. return [clock format $time -format "%Y-%m-%dT%H:%M:%SZ"]
  16. }
  17.  
  18. method log {message args} {
  19. variable template
  20. set props [dict merge $template $args]
  21. foreach {p script} {
  22. timestamp {clock seconds}
  23. } {
  24. if {![dict exists $props $p]} {
  25. dict set props $p [eval $script]
  26. }
  27. }
  28.  
  29. dict with props {
  30. set timestamp [my timestamp $timestamp]
  31. if {![string is integer -strict $facility]} {
  32. variable facilities
  33. set facility [dict get $facilities $facility]
  34. }
  35. if {![string is integer -strict $priority]} {
  36. variable priorities
  37. set priority [dict get $priorities $priority]
  38. }
  39. set PRI [expr {($facility * 8) + $priority}]
  40. set line "<$PRI>1 $timestamp $hostname $appname $procid $msgid - $message"
  41. #puts stderr $line
  42. }
  43. variable syslog; variable server; variable port
  44. ::udp send $syslog $server $port $line
  45. }
  46.  
  47. destructor {
  48. variable syslog
  49. catch {chan close $syslog}
  50. }
  51.  
  52. constructor {args} {
  53. variable facility user
  54. variable priority debug
  55. variable hostname [info host]
  56. variable procid [pid]
  57. variable appname $::argv0
  58. variable msgid -
  59. variable template {}
  60.  
  61. variable port 514 ;# syslog's port
  62.  
  63. variable {*}$args
  64.  
  65. if {![info exists server]} {
  66. error "must specify Syslog server"
  67. }
  68.  
  69. variable syslog [::udp create]
  70.  
  71. foreach v {hostname procid appname msgid facility priority} {
  72. if {![dict exists $template $v]} {
  73. dict set template $v [set $v]
  74. }
  75. }
  76.  
  77. variable facilities
  78. set i 0
  79. foreach f {
  80. kern user mail daemon auth syslog
  81. lrp news uucp cron authpriv ftp ntp audit alert clock
  82. local0 local1 local2 local3 local4 local5 local6 local7
  83. } {
  84. dict set facilities $f $i
  85. dict set facilities $i $f
  86. incr i
  87. }
  88.  
  89. variable priorities
  90. set i 0
  91. foreach f {emergency alert critical error warning notice info debug} {
  92. dict set priorities $f $i
  93. dict set priorities $i $f
  94. incr i
  95. }
  96. }
  97. }
  98.  
  99. if {[info exists argv0] && ($argv0 eq [info script])} {
  100. Syslog create syslog server box
  101. syslog log "This is a test"
  102. }