Uma consulta contextual localiza logs imediatamente antes e depois de um log-alvo de uma origem específica. Ao processar grandes volumes de logs, atribua um PackId para agrupar logs relacionados e recuperar o contexto de forma rápida e completa.
Como funciona
O PackId segue o formato prefixo contextual-ID do grupo de logs, por exemplo, 5FA51423DDB54FDA-1E3:
Prefixo contextual: dígitos hexadecimais maiúsculos, como
5FA51423DDB54FDA. Logs com o mesmo prefixo contextual pertencem ao mesmo contexto de log.ID do grupo de logs: dígitos hexadecimais maiúsculos, como
1E3. Dentro de um contexto de log, oID do grupo de logsincrementa sequencialmente. Por exemplo,1E3e1E4são grupos adjacentes.
O cliente gera um PackId e o envia com a solicitação de gravação de log. O Simple Log Service agrupa logs que compartilham um prefixo contextual no mesmo contexto de log.
Gerar PackId automaticamente
Logs gravados com um SDK producer: logs da mesma instância do producer compartilham um contexto e aceitam consultas contextuais. O Aliyun Log Java Producer e o C Producer SDK geram e anexam um PackId automaticamente.
Logs coletados pelo Logtail: o Logtail gera e anexa um PackId automaticamente. Logs do mesmo arquivo no mesmo host ou pod compartilham um contexto e aceitam consultas contextuais.
Gerar PackId manualmente com a API PutLogs
Parâmetros
Ao chamar a API PutLogs, inclua o PackId no atributo LogTags do LogGroup na solicitação PutLogs. Defina a Key como __pack_id__:
{
"Topic": "my-topic",
"Source": "127.0.0.1",
"LogTags": [
{
"Key": "__pack_id__",
"Value": "5FA51423DDB54FDA-1"
},
{
"Key": "my_other_tag_key",
"Value": "my_other_tag_value"
}
],
"Logs": [
{
"Time": 1728961415,
"Contents": [
{
"Key": "hello",
"Value": "world"
}
]
}
]
}
Código de exemplo
Exemplo em Java
-
Adicione as seguintes dependências ao arquivo pom.xml.
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>27.0.1-jre</version> </dependency> <dependency> <groupId>com.aliyun.openservices</groupId> <artifactId>aliyun-log</artifactId> <version>0.6.111</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>2.0.12</version> </dependency> -
Execute o código a seguir para gerar um PackId e enviá-lo pelo PutLogs. Substitua
project,logstore,endpoint,accessKeyIdeaccessKeySecretpelos valores reais.package org.example; import com.aliyun.openservices.log.Client; import com.aliyun.openservices.log.common.LogItem; import com.aliyun.openservices.log.common.TagContent; import com.aliyun.openservices.log.exception.LogException; import com.aliyun.openservices.log.request.PutLogsRequest; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.concurrent.atomic.AtomicLong; public class Main { private static final String TAG_PACK_ID = "__pack_id__"; private static final int TOKEN_LEN = 4; public static void main(String[] args) throws LogException { System.out.println("Hello world!"); // Use the same PackIdGenerator instance for the same context. PackIdGenerator generator1 = new PackIdGenerator(); System.out.println(generator1.generateNewPackId()); System.out.println(generator1.generateNewPackId()); System.out.println(generator1.generateNewPackId()); // Use different PackIdGenerator instances for different contexts. PackIdGenerator generator2 = new PackIdGenerator(); System.out.println(generator2.generateNewPackId()); System.out.println(generator2.generateNewPackId()); // Configure log parameters. String project = "your-project-name"; String logstore = "your-logstore-name"; String topic = "your-topic"; String source = "127.0.0.1"; Client client = new Client("your-endpoint", "your-access-key-id", "your-access-key-secret"); List<LogItem> logs = new ArrayList<>(); LogItem log = new LogItem(); log.PushBack("hello", "world"); logs.add(log); // Send a log request. PutLogsRequest req = new PutLogsRequest(project, logstore, topic, source, logs); // Add the PackId to the tag list. req.SetTags(Arrays.asList(new TagContent(TAG_PACK_ID, generator1.generateNewPackId()))); client.PutLogs(req); // Send another log request. PutLogsRequest req2 = new PutLogsRequest(project, logstore, topic, source, logs); req.SetTags(Arrays.asList(new TagContent(TAG_PACK_ID, generator1.generateNewPackId()))); client.PutLogs(req2); } public static class NetworkUtils { private NetworkUtils() { } public static boolean isIpAddress(final String ipAddress) { if (ipAddress == null || ipAddress.isEmpty()) { return false; } try { final String[] tokens = ipAddress.split("\\."); if (tokens.length != TOKEN_LEN) { return false; } for (String token : tokens) { int i = Integer.parseInt(token); if (i < 0 || i > 255) { return false; } } return true; } catch (Exception ex) { return false; } } public static String getLocalMachineIp() { try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface ni = networkInterfaces.nextElement(); if (!ni.isUp()) { continue; } Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { final InetAddress address = addresses.nextElement(); if (!address.isLinkLocalAddress() && address.getHostAddress() != null) { String ipAddress = address.getHostAddress(); if ("127.0.0.1".equals(ipAddress)) { continue; } if (isIpAddress(ipAddress)) { return ipAddress; } } } } } catch (SocketException ex) { // Ignore the exception. } return null; } } public static class PackIdGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(PackIdGenerator.class); private static final AtomicLong GENERATORID = new AtomicLong(0); private final String packIdPrefix; private final AtomicLong batchId = new AtomicLong(0); public PackIdGenerator() { packIdPrefix = generatePackIdPrefix(GENERATORID.getAndIncrement()).toUpperCase() + "-"; } public String generateNewPackId() { return packIdPrefix + Long.toHexString(batchId.getAndIncrement()).toUpperCase(); } private String generatePackIdPrefix(Long instanceId) { String ip = NetworkUtils.getLocalMachineIp(); if (ip == null) { LOGGER.warn("Failed to get local machine ip, set ip to 127.0.0.1"); ip = "127.0.0.1"; } String name = ManagementFactory.getRuntimeMXBean().getName(); String input = ip + "-" + name + "-" + instanceId; return Hashing.farmHashFingerprint64().hashString(input, Charsets.US_ASCII).toString(); } } }
Exemplo em Go
-
Instale o SDK do Go e a dependência protobuf.
go get -u github.com/aliyun/aliyun-log-go-sdk go get google.golang.org/protobuf -
Execute o código a seguir para gerar um PackId e enviá-lo pelo PutLogs. Substitua
project,logstore,endpoint,accessKeyIdeaccessKeySecretpelos valores reais.package main import ( "crypto/md5" "fmt" "os" "sync/atomic" "time" sls "github.com/aliyun/aliyun-log-go-sdk" "google.golang.org/protobuf/proto" ) func main() { // Use the same PackIdGenerator instance for the same context. g1 := NewPackIdGenerator() fmt.Println(g1.Generate()) fmt.Println(g1.Generate()) fmt.Println(g1.Generate()) // Use different PackIdGenerator instances for different contexts. g2 := NewPackIdGenerator() fmt.Println(g2.Generate()) fmt.Println(g2.Generate()) // Configure log parameters. project := "your-project-name" logstore := "your-logstore-name" topic := "your-topic" source := "your-source" client := sls.CreateNormalInterface("your-endpoint", "your-access-key-id", "your-access-key-secret", "") logs := []*sls.Log{ { Time: proto.Uint32(uint32(time.Now().Unix())), Contents: []*sls.LogContent{ { Key: proto.String("hello"), Value: proto.String("world"), }, { Key: proto.String("hi"), Value: proto.String("world"), }, }, }, } // Use the PostLogStoreLogsV2 operation to write logs. err := client.PostLogStoreLogsV2(project, logstore, &sls.PostLogStoreLogsRequest{ LogGroup: &sls.LogGroup{ Topic: &topic, Source: &source, Logs: logs, LogTags: []*sls.LogTag{ { Key: proto.String("__pack_id__"), // Add the PackId to the tag list. Value: proto.String(g1.Generate()), }, }, }, }) if err != nil { panic(err) } // Use the PutLogs operation to write logs. g1.Generate() creates a new PackId. err = client.PutLogs(project, logstore, &sls.LogGroup{ Topic: &topic, Source: &source, Logs: logs, LogTags: []*sls.LogTag{ { Key: proto.String("__pack_id__"), // Add the PackId to the tag list. Value: proto.String(g1.Generate()), }, }, }) if err != nil { panic(err) } } type PackIdGenerator struct { prefix string id atomic.Uint64 } func NewPackIdGenerator() *PackIdGenerator { return &PackIdGenerator{ prefix: generatePackIDPrefix(), id: atomic.Uint64{}, } } func (g *PackIdGenerator) Generate() string { return fmt.Sprintf("%s-%X", g.prefix, g.id.Add(1)) } // Generate context from the hostname, PID, and time. func generatePackIDPrefix() string { m := md5.New() m.Write([]byte(time.Now().String())) hostName, _ := os.Hostname() m.Write([]byte(hostName)) m.Write([]byte(fmt.Sprintf("%v", os.Getpid()))) return fmt.Sprintf("%X", m.Sum(nil)) }
Visualize contexto de log
-
No projeto, clique em no logstore desejado. Na aba , localize o log-alvo e clique em no ícone
.NotaLogs enviados via PutLogs com o mesmo prefixo contextual de PackId são agrupados no mesmo contexto de log. Clique em context view para exibir os grupos de logs que compartilham um prefixo contextual, com o log-alvo destacado.
Defina um intervalo de tempo, como 15 minutes, e clique em query / analyze.
-
Role a página para visualizar o contexto do log selecionado.
No painel context view, o log atual aparece destacado. Use older e newer para navegar pelos logs adjacentes. Selecione um campo em all fields ou insira uma palavra-chave para destacar as correspondências.
Referências
Visualize contexto de log no console: Consulta contextual.
Gravar logs por meio de SDK ou API: Usar o Aliyun Log Java Producer para gravar dados de log, C Producer SDK, PutLogs.