# 发出日志

> Add custom logging statements to your Cloud Code scripts and modules to record debugging information.

您可以从 [Cloud Code 脚本](../../scripts/overview)和[模块](../../modules/overview)发出日志。

## Cloud Code C# 模块##cloud-code-c-modules

您可以使用 [`Microsoft.Extensions.Logging` 库](https://learn.microsoft.com/en-us/dotnet/core/extensions/logging?tabs=command-line)从 [Cloud Code C# 模块](../../modules/overview)发出日志。每次您通过[依赖项注入](../../modules/how-to-guides/initialize-modules/dependency-injection)来请求 `ILogger` 时，Cloud Code 都会自动为您的代码提供 UGS Logger（UGS 日志记录器）。

以下代码示例显示了检测 C# 模块所需执行的所有操作：

```csharp
using Microsoft.Extensions.Logging;
using Unity.Services.CloudCode.Core;

namespace CloudCodeModules;

public class LoggingExample
{
    // Setting up the Dependency Injection. Cloud Code will inject a UGS Logger
    // into "_logger" which can then be used by all methods in this class
    private readonly ILogger<LoggingExample> _logger;
    public LoggingExample(ILogger<LoggingExample> logger)
    {
        _logger = logger;
    }

    [CloudCodeFunction("SayHello")]
    public string SayHello(IExecutionContext ctx, string name)
    {
        // Logging out a standard message
        _logger.LogDebug("received a request to SayHello");

        // Logging out a templated message. The template variable "name"
        // will be available as a key-value pair inside the log attributes map.
        // Templated keys cannot use dot notation for namespacing.
        _logger.LogInformation("saying hello to {name}", name);

        // A scope can be used to share sets of attributes between multiple log
        // entries. Attribute keys in a scope can use dot notation for namespacing
        // purposes.
        using (_logger.BeginScope(new Dictionary<string, object>
            {
                {"example.someInteger", 7 },
                {"example.someString", "frog blast the vent core!" }
            }))
        {
            _logger.LogInformation("logging within a scope");
            _logger.LogInformation("logging again with the same attributes");
        }

        return $"Hello, {name}!";
    }
}
```

## Cloud Code JavaScript 脚本##cloud-code-javascript-scripts

您可以使用脚本上下文中自动提供的默认日志记录器从 [Cloud Code JavaScript 脚本](../../scripts/overview)发出日志。

以下代码示例显示了检测 JavaScript 脚本所需执行的所有操作：

### JavaScript##javascript

```javascript
module.exports = async ({ params, context, logger }) => {
    logger.info("script executing", {"example.someString": "frog blast the vent core!"});
    logger.warning("this is a serious warning that the cheese is about to run out.");
    logger.error("out of cheese :(", {"example.foo": 42}, {"example.bar": 7});
};
```

该日志记录器提供以下方法：

* `debug(message, ...logAttributes)`
* `info(message, ...logAttributes)`
* `warning(message, ...logAttributes)`
* `error(message, ...logAttributes)`
* `fatal(message, ...logAttributes)`

### 限制##limits

每次调用可以传递多个日志属性，但是，存在以下限制：

* 每个日志属性必须是具有单个键/值对的对象。
* 该值必须是非空原语值（允许使用 false 布尔值）。
