Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. use tracing::{Subscriber, Event};
  2. use tracing::metadata::Metadata;
  3. use tracing::span::{Attributes, Id, Record as TracingRecord};
  4. use std::collections::{HashMap, hash_map::Entry};
  5. use std::sync::Mutex;
  6. use std::time::{Instant, Duration};
  7. use rand::Rng;
  8.  
  9. struct SpanData {
  10. name: &'static str,
  11. enter_time: Option<Instant>,
  12. }
  13. struct SpanTimerSubscriber {
  14. spans: Mutex<HashMap<Id, SpanData>>,
  15. }
  16. impl SpanTimerSubscriber {
  17. pub fn new() -> Self {
  18. SpanTimerSubscriber {
  19. spans: Mutex::new(HashMap::new())
  20. }
  21. }
  22. }
  23. impl tracing::Subscriber for SpanTimerSubscriber {
  24. fn enabled(&self, metadata: &tracing::metadata::Metadata<'_>) -> bool {
  25. true
  26. }
  27.  
  28. fn new_span(&self, span: &Attributes<'_>) -> Id {
  29. let span_data = SpanData {
  30. name: span.metadata().name(),
  31. enter_time: None,
  32. };
  33. let mut rng = rand::thread_rng();
  34. // will panic if you get 0 or a repeat, unlucky!
  35. let id = Id::from_u64(rng.gen::<u64>());
  36.  
  37. let mut mutex_guard = self.spans.lock().unwrap();
  38. mutex_guard.insert(id.clone(), span_data);
  39. id
  40. }
  41.  
  42. fn record(&self, _span: &Id, _values: &TracingRecord<'_>) {}
  43.  
  44. fn record_follows_from(&self, _span: &Id, _follows: &Id) {}
  45.  
  46. fn event(&self, _event: &Event<'_>) {}
  47.  
  48. fn enter(&self, span: &Id) {
  49. let mut hash_map = self.spans.lock().unwrap();
  50. match hash_map.entry(span.clone()) {
  51. Entry::Occupied(mut entry) => {
  52. let entry = entry.get_mut();
  53. if entry.enter_time.is_some() {
  54. panic!("Entered twice");
  55. }
  56. entry.enter_time = Some(Instant::now());
  57. }
  58. _ => panic!("Expected occupied entry for {:?}", span),
  59. }
  60. }
  61.  
  62. fn exit(&self, span: &Id) {
  63. let mut hash_map = self.spans.lock().unwrap();
  64. match hash_map.entry(span.clone()) {
  65. Entry::Occupied(mut entry) => {
  66. let entry = entry.get_mut();
  67. match entry.enter_time {
  68. None => panic!("Exited twice"),
  69. Some(enter_time) => {
  70. let exit_time = Instant::now();
  71. let duration = exit_time.duration_since(enter_time);
  72. if duration > Duration::from_millis(500) {
  73. println!("SPAN: '{}', DURATION: '{:?}'", entry.name, duration);
  74. }
  75. }
  76. }
  77. entry.enter_time = None;
  78. }
  79. _ => panic!("Expected occupied exit for {:?}", span),
  80. }
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement