Skip to content

Commit d7ef000

Browse files
committed
Add microsecond precision to quickstart logs
1 parent e50c7a3 commit d7ef000

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

samples/instrumentation-quickstart/app.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ def multi():
5858
def single():
5959
"""Handle an http request by sleeping for 100-200 ms, and write the number of seconds slept as the response."""
6060
duration = uniform(0.1, 0.2)
61+
logger.info("handle /single request", extra={"duration": duration})
6162
time.sleep(duration)
6263
return f"slept {duration} seconds"
6364

samples/instrumentation-quickstart/gcp_logging.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,25 @@
1313
# limitations under the License.
1414

1515
import logging
16+
from datetime import datetime
17+
from typing import Optional
1618

1719
from opentelemetry.instrumentation.logging import LoggingInstrumentor
1820
from pythonjsonlogger import jsonlogger
1921

2022

2123
# [START opentelemetry_instrumentation_setup_logging]
24+
class JsonFormatter(jsonlogger.JsonFormatter):
25+
def formatTime(self, record: logging.LogRecord, datefmt: Optional[str] = None):
26+
isoformat = datetime.fromtimestamp(record.created).isoformat()
27+
return f"{isoformat}Z"
28+
29+
2230
def setup_structured_logging() -> None:
2331
LoggingInstrumentor().instrument()
2432

2533
log_handler = logging.StreamHandler()
26-
formatter = jsonlogger.JsonFormatter(
34+
formatter = JsonFormatter(
2735
"%(asctime)s %(levelname)s %(message)s %(otelTraceID)s %(otelSpanID)s %(otelTraceSampled)s",
2836
rename_fields={
2937
"levelname": "severity",
@@ -32,7 +40,6 @@ def setup_structured_logging() -> None:
3240
"otelSpanID": "logging.googleapis.com/spanId",
3341
"otelTraceSampled": "logging.googleapis.com/trace_sampled",
3442
},
35-
datefmt="%Y-%m-%dT%H:%M:%SZ",
3643
)
3744
log_handler.setFormatter(formatter)
3845
logging.basicConfig(

0 commit comments

Comments
 (0)