1// Copyright (c) Meta Platforms, Inc. and its affiliates.
2// All rights reserved.
3//
4// This source code is licensed under the BSD-style license found in the
5// LICENSE file in the root directory of this source tree.
6
7#include <torch/csrc/distributed/c10d/debug.h>
8
9#include <algorithm>
10#include <cctype>
11#include <cstdlib>
12#include <string>
13
14#include <torch/csrc/distributed/c10d/exception.h>
15#include <torch/csrc/distributed/c10d/logging.h>
16
17namespace c10d {
18namespace detail {
19namespace {
20
21DebugLevel loadDebugLevelFromEnvironment() {
22 char* env_value = std::getenv("TORCH_DISTRIBUTED_DEBUG");
23
24 if (env_value == nullptr) {
25 return DebugLevel::Off;
26 }
27
28 DebugLevel level{};
29
30 std::string level_str{env_value};
31
32 std::transform(
33 level_str.begin(),
34 level_str.end(),
35 level_str.begin(),
36 [](unsigned char c) { return toupper(c); });
37
38 if (level_str == "OFF") {
39 level = DebugLevel::Off;
40 } else if (level_str == "INFO") {
41 level = DebugLevel::Info;
42 } else if (level_str == "DETAIL") {
43 level = DebugLevel::Detail;
44 } else {
45 throw C10dError{
46 "The value of TORCH_DISTRIBUTED_DEBUG must be OFF, INFO, or DETAIL."};
47 }
48
49 C10D_INFO("The debug level is set to {}.", level_str);
50
51 return level;
52}
53
54} // namespace
55} // namespace detail
56
57namespace {
58
59DebugLevel g_debug_level = DebugLevel::Off;
60
61} // namespace
62
63void setDebugLevel(DebugLevel level) {
64 g_debug_level = level;
65}
66
67void setDebugLevelFromEnvironment() {
68 g_debug_level = detail::loadDebugLevelFromEnvironment();
69}
70
71DebugLevel debug_level() noexcept {
72 return g_debug_level;
73}
74
75} // namespace c10d
76