Keycloak

Форк
0
/
logging.adoc 
516 строк · 20.3 Кб
1
<#import "/templates/guide.adoc" as tmpl>
2
<#import "/templates/kc.adoc" as kc>
3
<#import "/templates/links.adoc" as links>
4
<#import "/templates/profile.adoc" as profile>
5

6
<@tmpl.guide
7
title="Configuring logging"
8
summary="Learn how to configure Logging"
9
includedOptions="log log-*">
10

11
{project_name} uses the JBoss Logging framework. The following is a high-level overview for the available log handlers:
12

13
* root
14
** console (_default_)
15
** file
16
<@profile.ifCommunity>
17
** GELF
18
</@profile.ifCommunity>
19

20
== Logging configuration
21
Logging is done on a per-category basis in {project_name}. You can configure logging for the root log level or for more specific categories such as `org.hibernate` or `org.keycloak`. This {section} describes how to configure logging.
22

23
=== Log levels
24

25
The following table defines the available log levels.
26

27
[%autowidth]
28
|===
29
|Level|Description
30

31
|FATAL|Critical failures with complete inability to serve any kind of request.
32
|ERROR|A significant error or problem leading to the inability to process requests.
33
|WARN|A non-critical error or problem that might not require immediate correction.
34
|INFO|{project_name} lifecycle events or important information. Low frequency.
35
|DEBUG|More detailed information for debugging purposes, such as database logs. Higher frequency.
36
|TRACE|Most detailed debugging information. Very high frequency.
37
|ALL|Special level for all log messages.
38
|OFF|Special level to turn logging off entirely (not recommended).
39
|===
40

41
=== Configuring the root log level
42
When no log level configuration exists for a more specific category logger, the enclosing category is used instead. When there is no enclosing category, the root logger level is used.
43

44
To set the root log level, enter the following command:
45

46
<@kc.start parameters="--log-level=<root-level>"/>
47

48
Use these guidelines for this command:
49

50
* For `_<root-level>_`, supply a level defined in the preceding table.
51
* The log level is case-insensitive. For example, you could either use `DEBUG` or `debug`.
52
* If you were to accidentally set the log level twice, the last occurrence in the list becomes the log level. For example, if you included the syntax `--log-level="info,...,DEBUG,..."`, the root logger would be `DEBUG`.
53

54
=== Configuring category-specific log levels
55
You can set different log levels for specific areas in {project_name}. Use this command to provide a comma-separated list of categories for which you want a different log level:
56

57
<@kc.start parameters="--log-level=\"<root-level>,<org.category1>:<org.category1-level>\""/>
58

59
A configuration that applies to a category also applies to its sub-categories unless you include a more specific matching sub-category.
60

61
.Example
62
<@kc.start parameters="--log-level=\"INFO,org.hibernate:debug,org.hibernate.hql.internal.ast:info\""/>
63

64
This example sets the following log levels:
65

66
* Root log level for all loggers is set to INFO.
67
* The hibernate log level in general is set to debug.
68
* To keep SQL abstract syntax trees from creating verbose log output, the specific subcategory `org.hibernate.hql.internal.ast` is set to info. As a result, the SQL abstract syntax trees are omitted instead of appearing at the `debug` level.
69

70
== Enabling log handlers
71
To enable log handlers, enter the following command:
72

73
<@kc.start parameters="--log=\"<handler1>,<handler2>\""/>
74

75
The available handlers are
76
<@profile.ifCommunity>
77
`console`, `file` and `gelf`.
78
</@profile.ifCommunity>
79
<@profile.ifProduct>
80
`console` and `file`.
81
</@profile.ifProduct>
82
The more specific handler configuration mentioned below will only take effect when the handler is added to this comma-separated list.
83

84
== Console log handler
85
The console log handler is enabled by default, providing unstructured log messages for the console.
86

87
=== Configuring the console log format
88
{project_name} uses a pattern-based logging formatter that generates human-readable text logs by default.
89

90
The logging format template for these lines can be applied at the root level. The default format template is:
91

92
* `%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n`
93

94
The format string supports the symbols in the following table:
95

96
[%autowidth]
97
|===
98
|Symbol|Summary|Description
99

100
|%%|%|Renders a simple % character.
101
|%c|Category|Renders the log category name.
102
|++%d{xxx}++|Date|Renders a date with the given date format string.String syntax defined by `java.text.SimpleDateFormat`
103
|%e|Exception|Renders a thrown exception.
104
|%h|Hostname|Renders the simple host name.
105
|%H|Qualified host name|Renders the fully qualified hostname, which may be the same as the simple host name, depending on the OS configuration.
106
|%i|Process ID|Renders the current process PID.
107
|%m|Full Message|Renders the log message and an exception, if thrown.
108
|%n |Newline|Renders the platform-specific line separator string.
109
|%N|Process name|Renders the name of the current process.
110
|%p|Level|Renders the log level of the message.
111
|%r|Relative time|Render the time in milliseconds since the start of the application log.
112
|%s|Simple message|Renders only the log message without exception trace.
113
|%t|Thread name|Renders the thread name.
114
|%t++{id}++|Thread ID|Render the thread ID.
115
|%z{<zone name>}|Timezone|Set the time zone of log output to <zone name>.
116
|%L|Line number|Render the line number of the log message.
117
|===
118

119
=== Setting the logging format
120
To set the logging format for a logged line, perform these steps:
121

122
. Build your desired format template using the preceding table.
123
. Enter the following command:
124
+
125
<@kc.start parameters="--log-console-format=\"\'<format>\'\""/>
126

127
Note that you need to escape characters when invoking commands containing special shell characters such as `;` using the CLI. Therefore, consider setting it in the configuration file instead.
128

129
.Example: Abbreviate the fully qualified category name
130
<@kc.start parameters="--log-console-format=\"\'%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c{3.}] (%t) %s%e%n\'\""/>
131

132
This example abbreviates the category name to three characters by setting `[%c{3.}]` in the template instead of the default `[%c]`.
133

134
=== Configuring JSON or plain console logging
135
By default, the console log handler logs plain unstructured data to the console. To use structured JSON log output instead, enter the following command:
136

137
<@kc.start parameters="--log-console-output=json"/>
138

139
.Example Log Message
140
[source, json]
141
----
142
{"timestamp":"2022-02-25T10:31:32.452+01:00","sequence":8442,"loggerClassName":"org.jboss.logging.Logger","loggerName":"io.quarkus","level":"INFO","message":"Keycloak 18.0.0-SNAPSHOT on JVM (powered by Quarkus 2.7.2.Final) started in 3.253s. Listening on: http://0.0.0.0:8080","threadName":"main","threadId":1,"mdc":{},"ndc":"","hostName":"host-name","processName":"QuarkusEntryPoint","processId":36946}
143
----
144

145
When using JSON output, colors are disabled and the format settings set by `--log-console-format` will not apply.
146

147
To use unstructured logging, enter the following command:
148

149
<@kc.start parameters="--log-console-output=default"/>
150

151
.Example Log Message:
152
[source, bash]
153
----
154
2022-03-02 10:36:50,603 INFO  [io.quarkus] (main) Keycloak 18.0.0-SNAPSHOT on JVM (powered by Quarkus 2.7.2.Final) started in 3.615s. Listening on: http://0.0.0.0:8080
155
----
156

157
=== Colors
158
Colored console log output for unstructured logs is disabled by default. Colors may improve readability, but they can cause problems when shipping logs to external log aggregation systems. To enable or disable color-coded console log output, enter following command:
159

160
<@kc.start parameters="--log-console-color=<false|true>"/>
161

162
== File logging
163
As an alternative to logging to the console, you can use unstructured logging to a file.
164

165
=== Enable file logging
166
Logging to a file is disabled by default. To enable it, enter the following command:
167

168
<@kc.start parameters="--log=\"console,file\""/>
169

170
A log file named `keycloak.log` is created inside the `data/log` directory of your Keycloak installation.
171

172
=== Configuring the location and name of the log file
173

174
To change where the log file is created and the file name, perform these steps:
175

176
. Create a writable directory to store the log file.
177
+
178
If the directory is not writable, {project_name} will start correctly, but it will issue an error and no log file will be created.
179

180
. Enter this command:
181
+
182
<@kc.start parameters="--log=\"console,file\" --log-file=<path-to>/<your-file.log>"/>
183

184
=== Configuring the file handler format
185
To configure a different logging format for the file log handler, enter the following command:
186

187
<@kc.start parameters="--log-file-format=\"<pattern>\""/>
188

189
See <<Configuring the console log format>> for more information and a table of the available pattern configuration.
190

191
<@profile.ifCommunity>
192

193
== Centralized logging using GELF
194
NOTE: The support for GELF log handler is deprecated and will be removed in a future {project_name} release.
195

196
{project_name} can send logs to a centralized log management system such as the following:
197

198
* Graylog
199
* Logstash, inside the Elasticsearch, Logstash, Kibana (ELK) logging stack
200
* Fluentd, inside the Elasticsearch, Fluentd, Kibana (EFK) logging stack
201

202
{project_name} uses the https://quarkus.io/guides/centralized-log-management[Quarkus Logging GELF] extension to support these environments.
203

204
=== Enabling the GELF handler
205
To enable logging using GELF, add it to the list of activated log handlers.
206

207
.Example:
208
<@kc.start parameters="--log=\"console,gelf\""/>
209

210
=== Configuring the GELF handler
211

212
To configure the Host and Port of your centralized logging system, enter the following command and substitute the values with your specific values:
213
.Host and port of the GELF server:
214
<@kc.start parameters="--log=\"console,gelf\" --log-gelf-host=myhost --log-gelf-port=12345"/>
215

216
When the GELF handler is enabled, the host is using `localhost` as host value and UDP for communication. To use TCP instead of UDP, prefix the host value with `tcp:`. The Default port is `12201`.
217

218
.Include or exclude Stacktraces
219
{project_name} includes the complete Stacktrace inside the `StackTrace` field. To exclude this field, enter the following command:
220

221
<@kc.start parameters="--log=\"console,gelf\" --log-gelf-include-stack-trace=false"/>
222

223
.Configure the timestamp format
224
You can change the format of the `timestamp` field. For example, you can include the date and time down to seconds by entering the following command:
225

226
<@kc.start parameters="--log=\"console,gelf\" --log-gelf-timestamp-format=\"\'yyyy-MM-dd HH:mm:ss\'\""/>
227

228
Alternatively, you could use the config file to avoid escaping:
229

230
[source, conf]
231
----
232
log-gelf-timestamp-format=yyyy-MM-dd HH:mm:ss
233
----
234

235
The default timestamp format is `yyyy-MM-dd HH:mm:ss,SSS`. You can use the https://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html[available SimpleDateFormat patterns] to define an appropriate timestamp.
236

237
.Configure the facility
238
The `facility` field is an indicator of the process or program that is the source of log messages. The default value is `keycloak`. To set this field to your preferred identifier, enter the following command:
239

240
<@kc.start parameters="--log=\"console,gelf\" --log-gelf-facility=MyKeycloak"/>
241

242
To use the CLI to configure {project_name} and use whitespaces for `facility`, enter the following command:
243

244
<@kc.start parameters="--log=\"console,gelf\" --log-gelf-facility=\"\'my keycloak\'\""/>
245

246
Alternatively, you could use the config file to avoid escaping:
247

248
[source, conf]
249
----
250
log-gelf-facility=my keycloak
251
----
252

253
.Configure the default message size
254
To change the default message size of 8kb (8192 bytes) of GELF log messages for {project_name}, enter the following command:
255

256
<@kc.start parameters="--log=\"console,gelf\" --log-gelf-max-message-size=16384"/>
257

258
The maximum size of one GELF log message is set in Bytes. The preceding example increases the size to 16kb. When messages exceed the maximum size, GELF submits the message in multiple chunks.
259

260
.Configure sending of message parameters
261
{project_name} includes message parameters of the occurred log event. These fields appear in the output as `MessageParam0`, `MessageParam1`, and so on, depending on the parameter length.
262
To switch off this behavior, enter the following command:
263

264
<@kc.start parameters="--log=\"console,gelf\" --log-gelf-include-message-parameters=false"/>
265

266
.Configure sending of source code location
267
{project_name} includes the `SourceClassName`, `SourceMethodName` and `SourceSimpleClassName` fields in the GELF log messages. These fields provide detail on the location of an exception that occurred. To stop sending these fields, enter the following command:
268

269
<@kc.start parameters="--log=\"console,gelf\" --log-gelf-include-location=false"/>
270

271
=== Example: Send logs to Graylog
272
The following example shows how to send {project_name} logs to the Graylog centralized logging stack. This example assumes you have a container tool such as https://www.docker.com/[docker] installed to start the `compose.yml`.
273

274
==== Starting the Graylog stack
275
The composed stack consists of:
276

277
* Graylog
278
* ElasticSearch
279
* MongoDB
280

281
[source, yaml]
282
----
283
version: '3.8'
284

285
services:
286
  elasticsearch:
287
    image: docker.io/elastic/elasticsearch:7.10.2
288
    ports:
289
      - "9200:9200"
290
    environment:
291
      ES_JAVA_OPTS: "-Xms512m -Xmx512m"
292
      discovery.type: "single-node"
293
    networks:
294
      - graylog
295

296
  mongo:
297
    image: mongo:4.4
298
    networks:
299
      - graylog
300

301
  graylog:
302
    image: graylog/graylog:4.3.3
303
    ports:
304
      - "9000:9000"
305
      - "12201:12201/udp"
306
      - "1514:1514"
307
    environment:
308
      GRAYLOG_HTTP_EXTERNAL_URI: "http://127.0.0.1:9000/"
309
      # CHANGE ME (must be at least 16 characters)!
310
      GRAYLOG_PASSWORD_SECRET: "forpasswordencryption"
311
      # Password: admin
312
      GRAYLOG_ROOT_PASSWORD_SHA2: "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918"
313
    networks:
314
      - graylog
315
    depends_on:
316
      - elasticsearch
317
      - mongo
318

319
networks:
320
  graylog:
321
    driver: bridge
322
----
323

324
Copy and save the example locally into a `compose.yml` file and enter this command:
325

326
[source,bash]
327
----
328
docker compose up -d
329
----
330
After a few seconds, the Stack is ready to serve requests.
331

332
==== Creating a Graylog UDP Input
333
Once the stack is running, you need to create a UDP Input Graylog listens to. You can create it from the Graylog web UI (System → Input → Select GELF UDP) available at http://localhost:9000 or using the API:
334

335
This `curl` example creates a new GELF UDP Input using the API and the default Graylog login credentials (admin/admin).
336

337
[source, bash]
338
----
339
curl -H "Content-Type: application/json" -H "Authorization: Basic YWRtaW46YWRtaW4=" -H "X-Requested-By: curl" -X POST -v -d \
340
'{"title":"udp input","configuration":{"recv_buffer_size":262144,"bind_address":"0.0.0.0","port":12201,"decompress_size_limit":8388608},"type":"org.graylog2.inputs.gelf.udp.GELFUDPInput","global":true}' \
341
http://localhost:9000/api/system/inputs
342
----
343

344
If the stack is still in the bootstrap phase, you receive a response containing `* Empty reply from server`. A successful response includes `HTTP/1.1 201 Created` to indicate that the UDP input is created.
345

346
==== Configure {project_name} to send logs using GELF
347
{project_name} needs to be configured to send logs using GELF. The appropriate configuration can be seen in the following keycloak.conf example. The example includes the `log-gelf-host` and `log-gelf-port` values. These are optional values that are included for illustration purposes; default values exist.
348

349
.{project_name} GELF Configuration
350

351
[source, conf]
352
----
353
log=console,gelf
354
log-gelf-host=localhost
355
log-gelf-port=12201
356
----
357

358
==== Graylog: See the results
359
. Open your web browser, go to `http://localhost:9000`.
360
. Log in to the Graylog web UI using the administrator credentials (admin/admin).
361
. Go to Streams, All Messages.
362
. Start updating the stream by pressing the Play button in the upper right corner.
363
. Start {project_name} using `start` or `start-dev` and your GELF config.
364

365
After a few seconds, {project_name} messages appear in the Graylog dashboard.
366

367
=== Example Setup using the ELK Stack
368
The following example shows how to send {project_name} logs to the ELK centralized logging stack. It assumes you have a container tool such as https://www.docker.com/[docker] installed to start the `compose.yml`.
369

370
==== Enable the logstash GELF plugin and create a pipeline
371
Logstash uses an input plugin that understands and parses the GELF format. To activate this plugin when you are starting the ELK stack later on, create a directory `pipelines` and a file `gelf.conf` located in this directory. Then create an empty `compose.yml` in the parent directory.
372

373
.File Structure:
374
[source]
375
----
376
/ELK
377
  - compose.yml
378
  - pipelines/
379
    - gelf.conf
380
----
381

382

383
Add the following contents to `pipelines/gelf.conf` and save it:
384

385
[source, conf]
386
----
387
input {
388
  gelf {
389
    port => 12201
390
  }
391
}
392
output {
393
  stdout {}
394
  elasticsearch {
395
    hosts => ["http://elasticsearch:9200"]
396
  }
397
}
398
----
399

400
This file activates and configures the logstash GELF plugin and points it to the right elasticsearch instance.
401

402
==== Starting the ELK stack
403
The composed stack consists of:
404

405
* ElasticSearch
406
* Logstash
407
* Kibana
408

409
Copy the following content to your `compose.yml` file:
410

411
[source, yaml]
412
----
413
# Launch Elasticsearch
414
version: '3.8'
415

416
services:
417
  elasticsearch:
418
    image: docker.elastic.co/elasticsearch/elasticsearch-oss:6.8.2
419
    ports:
420
      - "9200:9200"
421
      - "9300:9300"
422
    environment:
423
      ES_JAVA_OPTS: "-Xms512m -Xmx512m"
424
    networks:
425
      - elk
426

427
  logstash:
428
    image: docker.elastic.co/logstash/logstash-oss:6.8.2
429
    volumes:
430
      - source: ./pipelines #the source dir gelf.conf resides
431
        target: /usr/share/logstash/pipeline
432
        type: bind
433
    ports:
434
      - "12201:12201/udp"
435
      - "5000:5000"
436
      - "9600:9600"
437
    networks:
438
      - elk
439
    depends_on:
440
      - elasticsearch
441

442
  kibana:
443
    image: docker.elastic.co/kibana/kibana-oss:6.8.2
444
    ports:
445
      - "5601:5601"
446
    networks:
447
      - elk
448
    depends_on:
449
      - elasticsearch
450

451
networks:
452
  elk:
453
    driver: bridge
454
----
455
Start the stack by entering the following command:
456

457
[source, bash]
458
----
459
docker compose up -d
460
----
461
After a few seconds the Stack should be ready to serve requests.
462

463
==== Configuring {project_name} to send logs using GELF
464
{project_name} needs to be configured to send logs using GELF. The appropriate configuration can be seen in the following keycloak.conf example. This example includes the `log-gelf-host` and `log-gelf-port` values. These are optional values, which are included for illustration purposes; default values exist.
465

466
.{project_name} Gelf Configuration
467

468
[source, conf]
469
----
470
log=console,gelf
471
log-gelf-host=localhost
472
log-gelf-port=12201
473
----
474

475
With this configuration applied, start {project_name} using `start-dev` or `start`.
476

477
==== Kibana: See the results
478
Open http://localhost:5601 to reach the Kibana dashboard. The exact configuration of a good monitoring dashboard is out of scope for this {section}. To find out if logs sent by {project_name} are delivered to Kibana, open the http://localhost:5601/app/kibana#/dev_tools/console?_g=()[Dev Tools] and execute the default `match_all` query. The logs should appear in the result field.
479

480
=== Configure a different log level for the GELF logger
481
To keep log storage costs and verbosity low, it is often wanted to only store a subset of the verbose application logs inside a centralized log management system. To configure {project_name} to use a different log level for the logs you want to ingest, use the following configuration:
482

483
[source, conf]
484
----
485
log=console,gelf
486
log-gelf-level=<desired-log-level>
487
...
488
----
489

490
.Example
491
To only see occurred log levels of warn and above in your centralized logging stack, but still see INFO level logs on the applications console logs, use the following configuration:
492

493
[source, conf]
494
----
495
log=console,gelf
496
log-level=INFO
497
log-gelf-level=warn
498
...
499
----
500

501
Looking at your ingested logs, you will see only messages of level warn or above will appear.
502

503
Keep in mind that `--log-level` is setting the leading log level, so for example when you invoke the following command:
504

505
<@kc.start parameters="--log=\"console,gelf\" --log-level=error --log-gelf-level=info"/>
506

507
nothing below the error level will be sent to your logging stack. That means that even GELF in this example will receive only error level log messages.
508

509
=== Configure additional key values
510
Currently, the {project_name} configuration does not support partly dynamic configuration keys, as they are used in quarkus properties. For example, they are used when defining `quarkus.log.handler.gelf.additional-field.<my-name>.value`.
511

512
To add user-defined fields, you can provide these fields through a quarkus.properties file. See <@links.server id="configuration"/> and the _Using raw Quarkus properties_ section.
513

514
</@profile.ifCommunity>
515

516
</@tmpl.guide>
517

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.