mirror of
https://github.com/facebook/sapling.git
synced 2024-10-10 08:47:12 +03:00
add a context manager API TelemetrySample
Summary: Add `__enter__()` and `__exit__()` methods to `TelemetrySample` so it can be used in `with` statements. It will automatically track the runtime for the body of the `with` context, and will record this in the `duration` field of the sample. It will also set the `success` field to True if the context exis normally and False if it exits due to an exception. On an exception the `error` field will also be populated with the exception message. Reviewed By: genevievehelsel Differential Revision: D20112723 fbshipit-source-id: d55ac3f1b53c23dc001f92a4f8eae431db8954e1
This commit is contained in:
parent
8ec16c8413
commit
3d1962ec1e
@ -15,8 +15,9 @@ import random
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
import types
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Tuple, Union
|
||||
from typing import Dict, List, Optional, Tuple, Type, Union
|
||||
|
||||
from . import version
|
||||
|
||||
@ -27,6 +28,28 @@ _session_id: Optional[int] = None
|
||||
|
||||
|
||||
class TelemetrySample(abc.ABC):
|
||||
_start_time: float = 0.0
|
||||
|
||||
def __enter__(self) -> "TelemetrySample":
|
||||
self._start_time = time.time()
|
||||
return self
|
||||
|
||||
def __exit__(
|
||||
self,
|
||||
exc_type: Optional[Type[BaseException]],
|
||||
exc_value: Optional[BaseException],
|
||||
exc_tracebac: Optional[types.TracebackType],
|
||||
) -> bool:
|
||||
duration = time.time() - self._start_time
|
||||
self.add_double("duration", duration)
|
||||
if exc_type is None:
|
||||
self.add_bool("success", True)
|
||||
else:
|
||||
self.add_bool("success", False)
|
||||
self.add_string("error", str(exc_value))
|
||||
self.log()
|
||||
return False
|
||||
|
||||
@abc.abstractmethod
|
||||
def add_int(self, name: str, value: int) -> "TelemetrySample":
|
||||
raise NotImplementedError()
|
||||
|
Loading…
Reference in New Issue
Block a user