bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 10쪽
64Counter
)
func init() {
var err error
myCounter, err = meter.Int64Counter("my.counter")
if err != nil {
panic(err)
}
}
func MyFunction(ctx context.Context) error {
ctx, span := tracer.Start(ctx, "MyFunction")
defer span.End()
myCounter.Add(ctx, 1)
// ... your code
return nil
}
```
### Shutdown
Always call `Shutdown()` when the application exits:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (a *App) Close() {
telemetry.Shutdown(ctx)
}
```
## Legacy API (Deprecated)
The package provides backward-compatible wrappers for `github.com/hashicorp/go-metrics`. These are **deprecated** and users should migrate to OpenTelemetry APIs directly.
### OpenTelemetry Bridge
Cosmos SDK v0.54.0+ provides a bridge to send existing go-metrics to the meter provider defined in your OpenTelemetry config.
To bridge your metrics, set the `metrics-sink` in `app.toml` to "otel".
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
###############################################################################
### Telemetry Configuration ###
###############################################################################
[telemetry]
# other fields...
metrics-sink = "otel"
```
### Legacy Configuration
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
cfg := telemetry.Config{
ServiceName: "my-service",
Enabled: true,
EnableHostname: true,
EnableHostnameLabel: true,
EnableServiceLabel: true,
PrometheusRetentionTime: 60, // seconds
GlobalLabels: [][]string{{"chain_id", "cosmoshub-1"}},
MetricsSink: "otel", // "mem", "statsd", "dogstatsd", "otel"
StatsdAddr: "localhost:8125",
}
m, err := telemetry.New(cfg)
```
### Legacy Metrics Functions
All are deprecated; prefer OpenTelemetry:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// Counters
telemetry.IncrCounter(1.0, "tx", "count")
telemetry.IncrCounterWithLabels([]string{"tx", "count"}, 1.0, labels)
// Gauges
telemetry.SetGauge(42.0, "mempool", "size")
telemetry.SetGaugeWithLabels([]string{"mempool", "size"}, 42.0, labels)
// Timing
start := telemetry.Now()
// ... operation
telemetry.MeasureSince(start, "tx", "process_time")
// Module-specific helpers
telemetry.ModuleMeasureSince("bank", start, "send", "time")
telemetry.ModuleSetGauge("bank", 100.0, "balance", "total")
```
## Metrics Sink Types
| Sink | Description |
| - | - |
| `mem` | In-memory sink with SIGUSR1 dump support (default) |
| `statsd` | StatsD protocol |
| `dogstatsd` | Datadog DogStatsD |
| `otel` | OpenTelemetry (bridges to configured MeterProvider) |
## Best Practices
1. **Use environment variable initialization** for production to avoid atomic load overhead
2. **Always call `Shutdown()`** to ensure metrics/traces are flushed
3. **Thread `context.Context`** properly for correct span correlation
## Viewing Telemetry Data
With Grafana LGTM running:
1. Open [http://localhost:3000](http://localhost:3000)
2. Use the Drilldown views to explore:
* **Traces**: Distributed trace visualization
* **Metrics**: Query and dashboard metrics
* **Logs**: Structured log search
## Related Documentation
* [OpenTelemetry Go SDK](https://opentelemetry.io/docs/languages/go/)
* [OpenTelemetry Configuration Spec](https://opentelemetry.io/docs/languages/sdk-configuration/declarative-configuration/)
* [otelconf Go Package](https://pkg.go.dev/go.opentelemetry.io/contrib/otelconf)
## Cosmos SDK Metrics
The following metrics are emitted from the Cosmos SDK.
| Metric | Description | Unit | Type |
| :- | :- | :- | :- |
| `tx_count` | Total number of txs processed via `FinalizeBlock` | tx | counter |
| `tx_successful` | Total number of successful txs processed via `FinalizeBlock` | tx | counter |
| `tx_failed` | Total number of failed txs processed via `FinalizeBlock` | tx | counter |
| `tx_gas_used` | The total amount of gas used by a tx | gas | gauge |
| `tx_gas_wanted` | The total amount of gas requested by a tx | gas | gauge |
| `tx_msg_send` | The total amount of tokens sent in a `MsgSend` (per denom) | token | gauge |
| `tx_msg_withdraw_reward` | The total amount of tokens withdrawn in a `MsgWithdrawDelegatorReward` (per denom) | token | gauge |
| `tx_msg_withdraw_commission` | The total amount of tokens withdrawn in a `MsgWithdrawValidatorCommission` (per denom) | token | gauge |
| `tx_msg_delegate` | The total amount of tokens delegated in a `MsgDelegate` | token | gauge |
| `tx_msg_begin_unbonding` | The total amount of tokens undelegated in a `MsgUndelegate` | token | gauge |
| `tx_msg_begin_begin_redelegate` | The total amount of tokens redelegated in a `MsgBeginRedelegate` | token | gauge |
| `tx_msg_ibc_transfer` | The total amount of tokens transferred via IBC in a `MsgTransfer` (source or sink chain) | token | gauge |
| `ibc_transfer_packet_receive` | The total amount of tokens received in a `FungibleTokenPacketData` (source or sink chain) | token | gauge |
| `new_account` | Total number of new accounts created | account | counter |
| `gov_proposal` | Total number of governance proposals | proposal | counter |
| `gov_vote` | Total number of governance votes for a proposal | vote | counter |
| `gov_deposit` | Total number of governance deposits for a proposal | deposit | counter |
| `staking_delegate` | Total number of delegations | delegation | counter |
| `staking_undelegate` | Total number of undelegations | undelegation | counter |
| `staking_redelegate` | Total number of redelegations | redelegation | counter |
| `ibc_transfer_send` | Total number of IBC transfers sent from a chain (source or sink) | transfer | counter |
| `ibc_transfer_receive` | Total number of IBC transfers received to a chain (source or sink) | transfer | counter |
| `ibc_client_create` | Total number of clients created | create | counter |
| `ibc_client_update` | Total number of client updates | update | counter |
| `ibc_client_upgrade` | Total number of client upgrades | upgrade | counter |
| `ibc_client_misbehaviour` | Total number of client misbehaviors | misbehaviour | counter |
| `ibc_connection_open-init` | Total number of connection `OpenInit` handshakes | handshake | counter |
| `ibc_connection_open-try` | Total number of connection `OpenTry` handshakes | handshake | counter |
| `ibc_connection_open-ack` | Total number of connection `OpenAck` handshakes | handshake | counter |
| `ibc_connection_open-confirm` | Total number of connection `OpenConfirm` handshakes | handshake | counter |
| `ibc_channel_open-init` | Total number of channel `OpenInit` handshakes | handshake | counter |
| `ibc_channel_open-try` | Total number of channel `OpenTry` handshakes | handshake | counter |
| `ibc_channel_open-ack` | Total number of channel `OpenAck` handshakes | handshake | counter |
| `ibc_channel_open-confirm` | Total number of channel `OpenConfirm` handshakes | handshake | counter |
| `ibc_channel_close-init` | Total number of channel `CloseInit` handshakes | handshake | counter |
| `ibc_channel_close-confirm` | Total number of channel `CloseConfirm` handshakes | handshake | counter |
| `tx_msg_ibc_recv_packet` | Total number of IBC packets received | packet | counter |
| `tx_msg_ibc_acknowledge_packet` | Total number of IBC packets acknowledged | acknowledgement | counter |
| `ibc_timeout_packet` | Total number of IBC timeout packets | timeout | counter |
| `store_iavl_get` | Duration of an IAVL `Store#Get` call | ms | summary |
| `store_iavl_set` | Duration of an IAVL `Store#Set` call | ms | summary |
| `store_iavl_has` | Duration of an IAVL `Store#Has` call | ms | summary |
| `store_iavl_delete` | Duration of an IAVL `Store#Delete` call | ms | summary |
| `store_iavl_commit` | Duration of an IAVL `Store#Commit` call | ms | summary |
| `store_iavl_query` | Duration of an IAVL `Store#Query` call | ms | summary |
# Writing CLI Commands
Source: https://docs.cosmos.network/sdk/latest/guides/tooling/autocli
<Note>
For a conceptual overview of how CLI, gRPC, and REST fit together in a Cosmos SDK app, see [CLI, gRPC & REST](/sdk/latest/learn/concepts/cli-grpc-rest).
</Note>
## Overview
`autocli` generates CLI commands and flags for each method defined in your gRPC service. By default, it generates a command for each gRPC service method. The commands are named based on the name of the service method.
The [API reference](/sdk/latest/api-reference/index) documents the services the standard modules define, which is what their generated commands call.
For example, given the following protobuf definition for a service:
```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
service MyService {
rpc MyMethod(MyRequest) returns (MyResponse) {}
}
```
The `autocli` package will generate a command named `my-method` for the `MyMethod` method. The command will have flags for each field in the `MyRequest` message.
It is possible to customize the generation of transactions and queries by defining options for each service.
## Application Wiring
Here are the steps to use AutoCLI:
1. Ensure your app's modules implement the `appmodule.AppModule` interface.
2. (optional) Configure how `autocli` behaves during command generation, by implementing the `func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions` method on the module.
3. Call `app.AutoCliOpts()` to get an `autocli.AppOptions` populated from the module manager, then set `ClientCtx` on it to wire in the keyring.
4. Call `EnhanceRootCommand()` to add the generated CLI commands to your root command.
<Tip>
AutoCLI is additive only, meaning *enhancing* the root command will only add subcommands that are not already registered. This means that you can use AutoCLI alongside other custom commands within your app.
</Tip>
In practice this looks like (from the [example chain](https://github.com/cosmos/example/blob/main/exampled/cmd/root.go)):
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
autoCliOpts := app.AutoCliOpts()
autoCliOpts.ClientCtx = initClientCtx // wires keyring + node connection
if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil {
panic(err)
}
```
### Keyring
AutoCLI resolves key names and signs transactions using the keyring from `client.Context`. At runtime, it reads the keyring from the command's live context (set by `SetCmdClientContextHandler` in `PersistentPreRunE` — see [Root Command Setup](#root-command-setup)) and adapts it to the [`cosmossdk.io/client/v2/autocli/keyring`](https://pkg.go.dev/cosmossdk.io/client/v2/autocli/keyring) interface via `keyring.NewAutoCLIKeyring` internally.
If no keyring is provided, AutoCLI-generated commands can still query the chain but cannot sign transactions.
<Tip>
Because AutoCLI resolves key names from the keyring, you can use account names directly instead of addresses:
```sh theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
<appd> q bank balances alice
<appd> tx bank send alice bob 1000denom
```
</Tip>
## Signing
`autocli` supports signing transactions with the keyring.
The [`cosmos.msg.v1.signer` protobuf annotation](/sdk/latest/guides/reference/protobuf-annotations) defines the signer field of the message.
This field is automatically filled when using the `--from` flag or defining the signer as a positional argument.
<Warning>
AutoCLI currently supports only one signer per transaction.
</Warning>
## Module wiring & Customization
The `AutoCLIOptions()` method on your module allows to specify custom commands, sub-commands or flags for each service, as it was a `cobra.Command` instance, within the `RpcCommandOptions` struct. Defining such options will customize the behavior of the `autocli` command generation, which by default generates a command for each method in your gRPC service.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
autocliv1.RpcCommandOptions{
RpcMethod: "Params", // The name of the gRPC service
Use: "params", // Command usage that is displayed in the help
Short: "Query the parameters of the governance process", // Short description of the command
Long: "Query the parameters of the governance process. Specify specific param types (voting|tallying|deposit)
to filter results.", // Long description of the command
PositionalArgs: []*autocliv1.PositionalArgDescriptor{
{
ProtoField: "params_type",
Optional: true
}, // Transform a flag into a positional argument
},
}
```
<Tip>
AutoCLI can create a gov proposal of any tx by simply setting the `GovProposal` field to `true` in the `autocliv1.RpcCommandOptions` struct.
Users can however use the `--no-proposal` flag to disable the proposal creation (which is useful if the authority isn't the gov module on a chain).
</Tip>
### Specifying Subcommands
By default, `autocli` generates a command for each method in your gRPC service. However, you can specify subcommands to group related commands together. To specify subcommands, use the `autocliv1.ServiceCommandDescriptor` struct.
For a real-world example, see the `gov` module's [`autocli.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/x/gov/autocli.go) in the Cosmos SDK. It demonstrates `ServiceCommandDescriptor` with `RpcCommandOptions`, `PositionalArgs`, `SubCommands`, `EnhanceCustomCommand`, and `GovProposal` all in one file.
### Positional Arguments
By default `autocli` generates a flag for each field in your protobuf message. However, you can choose to use positional arguments instead of flags for certain fields.
To add positional arguments to a command, use the `autocliv1.PositionalArgDescriptor` struct, as seen in the example below. Specify the `ProtoField` parameter, which is the name of the protobuf field that should be used as the positional argument. In addition, if the parameter is a variable-length argument, you can specify the `Varargs` parameter as `true`. This can only be applied to the last positional parameter, and the `ProtoField` must be a repeated field.
For a real-world example, see the `auth` module's [`autocli.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/x/auth/autocli.go) in the Cosmos SDK. It shows positional args wired for every query method, with `address` as a positional argument on the `Account` method.
After wiring positional args, the command can be used as follows, instead of having to specify the `--address` flag:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
<appd> query auth account cosmos1abcd...xyz
```
#### Flattened Fields in Positional Arguments
AutoCLI also supports flattening nested message fields as positional arguments. This means you can access nested fields
using dot notation in the `ProtoField` parameter. This is particularly useful when you want to directly set nested
message fields as positional arguments.
For example, if you have a nested message structure like this:
```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
message Permissions {
string level = 1;
repeated string limit_type_urls = 2;
}
message MsgAuthorizeCircuitBreaker {
string grantee = 1;
Permissions permissions = 2;
}
```
You can flatten the fields in your AutoCLI configuration:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
{
RpcMethod: "AuthorizeCircuitBreaker",
Use: "authorize [grantee] [level] [msg_type_urls]",
PositionalArgs: []*autocliv1.PositionalArgDescriptor{
{ProtoField: "grantee"},
{ProtoField: "permissions.level"},
{ProtoField: "permissions.limit_type_urls", Varargs: true},
},
}
```
This allows users to provide values for nested fields directly as positional arguments:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
<appd> tx circuit authorize cosmos1... super-admin "/cosmos.bank.v1beta1.MsgSend" "/cosmos.bank.v1beta1.MsgMultiSend"
```
Instead of having to provide a complex JSON structure for nested fields, flattening makes the CLI more user-friendly by allowing direct access to nested fields.
#### Customizing Flag Names
By default, `autocli` generates flag names based on the names of the fields in your protobuf message. However, you can customize the flag names by providing a `FlagOptions`. This parameter allows you to specify custom names for flags based on the names of the message fields.
For example, if you have a message with the fields `test` and `test1`, you can use the following naming options to customize the flags:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
autocliv1.RpcCommandOptions{
FlagOptions: map[string]*autocliv1.FlagOptions{
"test": {
Name: "custom_name",
},
"test1": {
Name: "other_name",
},
},
}
```
### Combining AutoCLI with Other Commands Within A Module
AutoCLI can be used alongside other commands within a module. For example, the `gov` module uses AutoCLI for its query commands while also keeping hand-written tx commands for `submit-proposal`, `weighted-vote`, and similar.
Set `EnhanceCustomCommand: true` on each `ServiceCommandDescriptor` where you want AutoCLI to add generated commands alongside existing ones:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions {
return &autocliv1.ModuleOptions{
Query: &autocliv1.ServiceCommandDescriptor{
Service: govv1.Query_ServiceDesc.ServiceName,
EnhanceCustomCommand: true, // keep hand-written gov query commands
RpcCommandOptions: []*autocliv1.RpcCommandOptions{ /* ... */ },
},
Tx: &autocliv1.ServiceCommandDescriptor{
Service: govv1.Msg_ServiceDesc.ServiceName,
EnhanceCustomCommand: true, // keep hand-written gov tx commands
},
}
}
```
If `EnhanceCustomCommand` is not set to `true`, AutoCLI skips command generation for any service that already has commands registered via `GetTxCmd()` or `GetQueryCmd()`.
### Skip a command
AutoCLI checks the [`cosmos_proto.method_added_in` protobuf annotation](/sdk/latest/guides/reference/protobuf-annotations) and skips commands that were introduced in a newer SDK version than the one currently running.
Additionally, a command can be manually skipped using the `autocliv1.RpcCommandOptions`:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
autocliv1.RpcCommandOptions{
RpcMethod: "Params", // The name of the gRPC method
Skip: true,
}
```
### Use AutoCLI for non module commands
It is possible to use `AutoCLI` for non-module commands. The pattern is to add the options directly to `autoCliOpts.ModuleOptions` after calling `AutoCliOpts()`:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
nodeCmds := nodeservice.NewNodeCommands()
autoCliOpts.ModuleOptions[nodeCmds.Name()] = nodeCmds.AutoCLIOptions()
```
`AutoCliOpts()` only picks up modules registered with the module manager — non-module commands always need to be added to `ModuleOptions` manually, as the example chain does with `nodeservice.NewNodeCommands()`.
For a more complete example of this pattern, see [`client/grpc/cmtservice/autocli.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/client/grpc/cmtservice/autocli.go) and [`client/grpc/node/autocli.go`](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/client/grpc/node/autocli.go) in the Cosmos SDK.
## Root Command Setup
For AutoCLI-generated commands (and hand-written commands) to work correctly — signing transactions, querying the chain, reading configuration — the root command must set up the `client.Context` and `server.Context` in a `PersistentPreRunE` function. This runs before every subcommand and makes both cont프로젝트로 돌아가기