Skip to content

Commit 1d6a1a7

Browse files
authored
Update serving.py
- Added a new function 'configure_logging()' to dynamically set log levels - Utilize TS_LOGLEVEL environment variable to control logging verbosity - Support log levels: OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE - Modify log4j2.xml file using sed command based on TS_LOGLEVEL - Handle potential errors during log configuration gracefully - Call configure_logging() before starting TorchServe - Aim to reduce excessive logging and associated CloudWatch costs - Maintain default logging if TS_LOGLEVEL is not set or invalid
1 parent cc8bf99 commit 1d6a1a7

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

src/sagemaker_pytorch_serving_container/serving.py

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# language governing permissions and limitations under the License.
1313
from __future__ import absolute_import
1414

15+
import os
16+
import subprocess
1517
from subprocess import CalledProcessError
1618

1719
from retrying import retry
@@ -20,11 +22,35 @@
2022

2123
HANDLER_SERVICE = handler_service.__file__
2224

25+
def configure_logging():
26+
log_levels = {
27+
'0': 'off',
28+
'10': 'fatal',
29+
'20': 'error',
30+
'30': 'warn',
31+
'40': 'info',
32+
'50': 'debug',
33+
'60': 'trace'
34+
}
35+
36+
ts_loglevel = os.environ.get('TS_LOGLEVEL')
37+
38+
if ts_loglevel is not None:
39+
if ts_loglevel in log_levels:
40+
try:
41+
log_level = log_levels[ts_loglevel]
42+
subprocess.run(['sed', '-i', f's/info/{log_level}/g', 'etc/log4j2.xml'], check=True)
43+
print(f"Logging level set to {log_level}")
44+
except subprocess.CalledProcessError:
45+
print("Error configuring the logging", file=sys.stderr)
46+
else:
47+
print(f"Invalid TS_LOGLEVEL value: {ts_loglevel}. No changes made to logging configuration.", file=sys.stderr)
48+
else:
49+
print("TS_LOGLEVEL not set. Using default logging configuration.")
2350

2451
def _retry_if_error(exception):
2552
return isinstance(exception, CalledProcessError)
2653

27-
2854
@retry(stop_max_delay=1000 * 30,
2955
retry_on_exception=_retry_if_error)
3056
def _start_torchserve():
@@ -33,6 +59,9 @@ def _start_torchserve():
3359
# retry starting mms until it's ready
3460
torchserve.start_torchserve(handler_service=HANDLER_SERVICE)
3561

36-
3762
def main():
63+
configure_logging()
3864
_start_torchserve()
65+
66+
if __name__ == '__main__':
67+
main()

0 commit comments

Comments
 (0)