> For the complete documentation index, see [llms.txt](https://docs.scepman.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.scepman.com/pt/configuracao-do-azure/log-configuration.md).

# Gestão de registos

### Ativar o registo no Azure Monitor

Desde a versão 3.0, o SCEPman e o Certificate Master usam a Log Ingestion API da Microsoft para enviar registos para o Azure Monitor. Os registos são armazenados num Log Analytics Workspace, e uma Data Collection Rule liga os App Services ao workspace. Esta abordagem moderna usa permissões baseadas em RBAC para o SCEPman aceder à LAW.

A criação de um Log Analytics Workspace, bem como a configuração da Data Collection Rule, é feita automaticamente ao executar `Complete-SCEPmanInstallation` do módulo PowerShell do SCEPman.

```
Install-Module SCEPman -Scope CurrentUser -Force
Complete-SCEPmanInstallation 6>&1
```

{% hint style="info" %}
O **período de retenção predefinido** para os dados armazenados numa Log Analytics Table é **30 dias**. Caso seja necessário um período de retenção diferente, ajuste a configuração da Table "SCEPman\_CL" em conformidade.
{% endhint %}

#### Reativação da API Data Collector

Se, por qualquer motivo, quiser reinstaurar a API anterior a ser utilizada, pode fazê-lo removendo as variáveis do App Service relacionadas com Log Ingestion e adicionando novamente as que serão utilizadas pela Data Collector API.

Variáveis a serem **removidas**:

* [AppConfig:LoggingConfig:DataCollectionEndpointUri](/pt/configuracao-do-scepman/application-settings/dependencies-azure-services/logging.md#appconfig-loggingconfig-datacollectionendpointuri)
* [AppConfig:LoggingConfig:RuleId](/pt/configuracao-do-scepman/application-settings/dependencies-azure-services/logging.md#appconfig-loggingconfig-ruleid)

Variáveis a adicionar:

* [AppConfig:LoggingConfig:WorkspaceId](/pt/configuracao-do-scepman/application-settings/dependencies-azure-services/logging.md#appconfig-loggingconfig-workspaceid)
* [AppConfig:LoggingConfig:SharedKey](/pt/configuracao-do-scepman/application-settings/dependencies-azure-services/logging.md#appconfig-loggingconfig-sharedkey)

O SCEPman irá automaticamente aplicar as definições após um reinício e voltará a utilizar a Data Collector API.

## Exemplos de consultas KQL

### Ver problemas com a sua instância do SCEPman

```kusto
SCEPman_CL
| where Level == "Warn" or Level == "Error" or Level == "Fatal"
```

### Número de certificados emitidos por endpoint no período de tempo selecionado

{% hint style="success" %}
Esta consulta tem garantia de funcionamento com o SCEPman 3.0 e versões posteriores quando se utiliza a Log Ingestion API para registo. Alterações ao SCEPman que tornem esta consulta inutilizável serão consideradas Breaking Changes.
{% endhint %}

{% tabs %}
{% tab title="Log Ingestion API ( Predefinida )" %}

```kql
SCEPman_CL
| where Level == "Info" and Message startswith_cs "Issued a certificate with serial number"
| project Message, RequestBase = trim_end('/', replace_string(replace_string(replace_regex(RequestUrl, "(/pkiclient\\.exe)?(\\?operation=PKIOperation(&message=.+)?)?", ""),"certsrv/mscep/mscep.dll","intune"),"step/enrollment","activedirectory"))
| summarize IssuanceCount = count() by Endpoint = extract("/([a-zA-Z]+)$", 1, RequestBase)
```

{% endtab %}

{% tab title="Data Collector API ( Antiga )" %}

```kusto
SCEPman_CL
| where Level == "Info" and Message startswith_cs "Issued a certificate with serial number"
| project Message, RequestBase = trim_end('/', replace_string(replace_string(replace_regex(RequestUrl_s, "(/pkiclient\\.exe)?(\\?operation=PKIOperation(&message=.+)?)?", ""),"certsrv/mscep/mscep.dll","intune"),"step/enrollment","activedirectory"))
| summarize IssuanceCount = count() by Endpoint = extract("/([a-zA-Z]+)$", 1, RequestBase)
```

{% endtab %}
{% endtabs %}

A partir do SCEPman 2.8, existe sempre exatamente uma entrada de registo de nível Info cuja mensagem de registo começa com "Issued a certificate with serial number " por cada certificado emitido, seguida do respetivo número de série. No entanto, devido ao insolúvel [Problema dos Dois Exércitos](https://en.wikipedia.org/wiki/Two_Generals'_Problem), pode acontecer que o certificado criado nunca chegue ao requerente ou que algum outro tipo de erro impeça o registo efetivo. Do mesmo modo, em caso de erros graves, pode acontecer que exista uma entrada de registo sem a entrada correspondente na base de dados ou vice-versa.

### Certificados distintos com verificação OCSP

{% tabs %}
{% tab title="Log Ingestion API ( Predefinida )" %}

```kusto
let map_certtype = datatable(serial_start:string, readable:string)
[
  "40", "Dispositivo Intune",
  "41", "Dispositivo Intune",
  "42", "Dispositivo Intune não conforme",
  "50", "Estático",
  "51", "Estático",
  "60", "Utilizador Intune",
  "61", "Utilizador Intune",
  "64", "Utilizador Jamf",
  "65", "Utilizador Jamf",
  "6C", "Utilizador Jamf no dispositivo",
  "6D", "Utilizador Jamf no dispositivo",
  "70", "Domain Controller",
  "7C", "Utilizador Jamf no computador",
  "7D", "Utilizador Jamf no computador",
  "54", "Computador Jamf",
  "55", "Computador Jamf",
  "44", "Dispositivo Jamf",
  "45", "Dispositivo Jamf"
];
SCEPman_CL
| where LogCategory == "Scepman.Server.Controllers.OcspController" and Level == "Info"
| where Message startswith_cs "OCSP Response"
| project serial = extract("Serial Number ([A-F0-9]+)", 1, Message)
| distinct serial
| extend serial_start = substring(serial,0,2)
| join kind=leftouter map_certtype on serial_start
| summarize count() by (readable)
```

{% endtab %}

{% tab title="Data Collector API ( Antiga )" %}

```kql
let map_certtype = datatable(serial_start:string, readable:string)
[
  "40", "Dispositivo Intune",
  "41", "Dispositivo Intune",
  "42", "Dispositivo Intune não conforme",
  "50", "Estático",
  "51", "Estático",
  "60", "Utilizador Intune",
  "61", "Utilizador Intune",
  "64", "Utilizador Jamf",
  "65", "Utilizador Jamf",
  "6C", "Utilizador Jamf no dispositivo",
  "6D", "Utilizador Jamf no dispositivo",
  "70", "Domain Controller",
  "7C", "Utilizador Jamf no computador",
  "7D", "Utilizador Jamf no computador",
  "54", "Computador Jamf",
  "55", "Computador Jamf",
  "44", "Dispositivo Jamf",
  "45", "Dispositivo Jamf"
];
SCEPman_CL
| where LogCategory_s == "Scepman.Server.Controllers.OcspController" and Level == "Info"
| where Message startswith_cs "OCSP Response"
| project serial = extract("Serial Number ([A-F0-9]+)", 1, Message)
| distinct serial
| extend serial_start = substring(serial,0,2)
| join kind=leftouter map_certtype on serial_start
| summarize count() by (readable)
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.scepman.com/pt/configuracao-do-azure/log-configuration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
