Skip to content

Commit ed73fb2

Browse files
tg359Fraser Greenroyd
authored andcommitted
updated analytics method
1 parent ae07c7a commit ed73fb2

File tree

2 files changed

+13
-77
lines changed

2 files changed

+13
-77
lines changed
Lines changed: 1 addition & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1 @@
1-
from __future__ import annotations
2-
3-
import functools
4-
import inspect
5-
import socket
6-
import sys
7-
import traceback
8-
from datetime import date, datetime
9-
from json import JSONEncoder, dump
10-
from pathlib import Path
11-
from uuid import uuid4
12-
13-
import numpy as np
14-
import pandas as pd
15-
16-
17-
class BHoMJSONEncoder(JSONEncoder):
18-
"""A custom BHoM JSONEncoder class capable of serialising non-native Python datatypes into a JSONable object."""
19-
20-
def default(self, obj):
21-
if isinstance(obj, np.ndarray):
22-
return obj.tolist()
23-
if isinstance(obj, (pd.Series, pd.DataFrame)):
24-
return obj.to_dict()
25-
if isinstance(obj, (datetime, date)):
26-
return obj.isoformat()
27-
if isinstance(obj, Path):
28-
return obj.as_posix()
29-
return JSONEncoder.default(self, obj)
30-
31-
32-
def bhom_analytics(f):
33-
"""A wrapper function used to capture usage analytics of the wrapped function"""
34-
35-
@functools.wraps(f)
36-
def wrapper(*args, **kwds):
37-
output_file = Path(f"C:/Temp/bhom_python_{uuid4()}.json")
38-
d = {
39-
"StartTime": datetime.now(),
40-
"Computer": socket.gethostname(),
41-
"FileName": Path(inspect.getfile(f)).as_posix(),
42-
"UiVersion": sys.version,
43-
"UI": Path(sys.executable).as_posix(),
44-
"SelectedItem": f.__name__,
45-
"Errors": [],
46-
}
47-
# run function and obtain errors if it failed
48-
try:
49-
d["Result"] = f(*args, **kwargs)
50-
except Exception:
51-
d["Errors"].append(traceback.format_exc())
52-
d["Result"] = None
53-
d["EndTime"] = datetime.now()
54-
55-
# TODO - make this JSON dump into an in-memory location to save on file IO overhead.
56-
with open(output_file, "w+") as fp:
57-
dump(d, fp, cls=BHoMJSONEncoder)
58-
# print function here to enable downstream processes to access the location where the data is stored for loading into BHoM.
59-
print(output_file, file=sys.stdout)
60-
61-
return f(*args, **kwds)
62-
63-
return wrapper
1+


Python_Engine/Python/src/python_toolkit/bhom/analytics.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import inspect
33
import sys
44
import traceback
5-
from json import dump
65
from pathlib import Path
76
from typing import Callable
87
from uuid import uuid4
@@ -14,26 +13,25 @@
1413
ASSEMBLIES_DIR = Path(r"C:\ProgramData\BHoM\Assemblies")
1514
LOGGING_DIR = Path(r"C:\ProgramData\BHoM\Logs")
1615
LOGGING_DIR.mkdir(exist_ok=True, parents=True)
16+
BHOM_VERSION = ".".join([str(i) for i in version((ASSEMBLIES_DIR / "BHoM.dll").as_posix())][:2])
17+
UI_NAME = "PythonBHoM"
18+
TICKS = ticks()
1719

1820

1921
def analytics(f: Callable):
2022
"""A wrapper used to capture usage analytics of the decorated function."""
2123

2224
@functools.wraps(f)
2325
def wrapper(*args, **kwargs):
24-
25-
bhom_version = ".".join([str(i) for i in version((ASSEMBLIES_DIR / "BHoM.dll").as_posix())][:2])
26-
ui_name = "PythonBHoM"
27-
ticks_value = ticks()
2826

2927
_, module_stack, _, file_path = str(inspect.getmodule(f)).split(" ")
3028
module_stack = module_stack[1:-1]
3129

32-
log_file = LOGGING_DIR / f"Usage_{ui_name}_{ticks_value}.log"
30+
log_file = LOGGING_DIR / f"Usage_{UI_NAME}_{TICKS}.log"
3331

3432
# gather metadata around current callable instance
3533
d = {
36-
"BHoMVersion": bhom_version,
34+
"BHoMVersion": BHOM_VERSION,
3735
"BHoM_Guid": str(uuid4()),
3836
"CallerName": f"{module_stack}",
3937
"ComponentId": "",
@@ -47,17 +45,17 @@ def wrapper(*args, **kwargs):
4745
"SelectedItem":
4846
{
4947
"Name": f.__name__,
50-
"_bhomVersion": bhom_version,
48+
"_bhomVersion": BHOM_VERSION,
5149
"_t": "Python"
5250
},
5351
"Tags": [],
5452
"Time":
5553
{
56-
"$date": ticks_value
54+
"$date": TICKS
5755
},
58-
"UI": ui_name,
56+
"UI": UI_NAME,
5957
"UiVersion": sys.version,
60-
"_bhomVersion": bhom_version,
58+
"_bhomVersion": BHOM_VERSION,
6159
"_t": "BH.oM.UI.UsageLogEntry"
6260
}
6361

@@ -67,11 +65,11 @@ def wrapper(*args, **kwargs):
6765
except Exception:
6866
d["Errors"].append(traceback.format_exc())
6967

70-
with open(log_file, "w+") as fp:
71-
dump(d, fp, cls=Encoder)
68+
with open(log_file, "a+") as fp:
69+
fp.write(str(d) + "\n")
7270

7371
# print function here to enable downstream processes to access the location where the data is stored for loading into BHoM.
74-
print(log_file, file=sys.stdout)
72+
#print(log_file, file=sys.stdout)
7573

7674
return f(*args, **kwargs)
7775

0 commit comments

Comments
 (0)