Skip to main content

Advanced Configuration: Configuration File Reference

T hingsGatewayRuntime runtime configuration is by default located in the GatewayApp/Configuration/ directory. At startup, appsettings.json is loaded, then merged with the JSON configuration under Configuration/; In production deployment, parameters such as port, database, JWT key (the signing key for login tokens), and log retention policies should be prioritized through configuration files or environment variables.

Scope of Application

This page is not the primary reading path for general end users, but is intended for site administrators, delivery engineers, system integration engineers, and operations and maintenance personnel. General data collection, meter counting, alarms, data forwarding, and debugging should be prioritized on the web page; It is only recommended to directly modify the JSON configuration when it is necessary to adjust service ports, database connections, JWT keys, cross-origin sources, log retention policies, or initialization policies. Before modifying, back up the configuration and database, then restart GatewayRuntime via the on-site maintenance window.

First, look at the terminology

TerminologyOn-site understanding
JSON Configure the text configuration file read when thegateway starts. After modification, you usually need to restart GatewayRuntime for it to take effect.
Environment VariableConfiguration value provided by the operating system or startup script, commonly used to store passwords, keys, and other content that is not suitable for writing to files.
JWT / TokenAccess credentials and their signature rules after login. Leaking JWT keys or reusing default values can affect account security.
CORS / Cross-origin SourceWhich frontend addresses the browser allows to access the gateway API. Limiting errors can cause pages or third-party systems to be unable to call the interface.
SQLite / WALSQLite is a local database file; WAL is a logging mode for concurrent read/write at runtime. Pay attention to related files when backing up.
OAuth2 / PKCEThird-party login mechanism and its security verification method. Before activating, confirm the callback address, client ID, key, and HTTPS.
Snowflake IDalgorithm that generates a unique number by the system. Ordinary on-site configurations generally do not require adjustment.
SeedDataInitialize basic data such as users, roles, and menus. Do not forcibly refresh the production environment.

Configuration File List

FilePurpose
WebApiOptions.jsonGatewayRuntime Web/API Service Port and Cross-origin Source
Database.jsonDefault Business Library, Backend Log Library, Operation Log Library, SQL Log Library Connection
LoggerOptions.jsonProcess Logs, Gateway Business Logs, Backend Management Log Retention Policy, and ASP.NET Log Level
JWTOptions.jsonJWT issuer, expiration time, algorithm, type, and key
ChannelThread.jsonChannel inspection interval and capacity limits for channels, devices, and variables
IdGeneratorOptions.jsonSnowflake ID generator algorithm, time benchmark, machine number, and serial bit configuration
OAuth2Options.jsonOAuth2 login, callback address, default roles, and third-party providers
SeedDataOptions.jsonWhether initialization data forcibly refreshes users, roles, menus, buttons, etc.
*.Development.jsonOverlay configuration for local debugging or test deployments; production deployments generally do not use

Directory structure

DirectoryDescription
DB/Default business database directory, default SQLite file is ThingsGateway.db
OTHERDB/Background logs, operation logs, SQL logs, and other auxiliary database directories
Configuration/Runtime configuration file directory
Logs/Runtime log directory, specific path subject to log configuration
GatewayApp/GatewayRuntime program directory, it is not recommended to manually move or clean up during runtime

WebApiOptions

WebApiOptions.json Used to set listening ports and allowed access sources for GatewayRuntime Web/API.

Configuration ItemsDescriptionDefault Values
PortGatewayRuntime Web/API Listening Port6100
CorsOriginsOrigins allowed to access the GatewayRuntime API from a browser. Leave blank to allow all origins. To restrict access, enter a complete origin such as http://192.168.1.10:3000, including the scheme, domain name or IP address, and port, without a path.Empty string

modify Port and restart GatewayRuntime. When deploying under Watchdog, you also need to synchronously confirm the Gateway API port configuration in Watchdog.

Database

Database.json configured for business and log database connections. By default, SQLite is deployed, but you can also switch to other databases as required by the site.

ConfigIdDefault ConnectionPurpose
DefaultData Source=DB/ThingsGateway.db;journal mode=WALCore data such as business configuration, channels, devices, variables, scripts, nodes
BackendData Source=OTHERDB/Backend.db;journal mode=WALBackend logs, channel logs, device logs, rule logs, data forwarding logs, etc.
OperateData Source=OTHERDB/Operate.db;journal mode=WALOperation logs, RPC logs, audit-related records
SqlLogData Source=OTHERDB/SqlLog.db;journal mode=WALSQL execution log

B y default, SQLite connects strings explicitly enable WAL log mode to enhance runtime read-write concurrency. When migrating, backing up, or copying SQLite files, attention should be paid to both the main database file and any possible running -wal, -shm files; Before switching to another database, back up the original database and confirm that the target database account, network, firewall, and initialization permissions are available.

LoggerOptions

LoggerOptions.json Includes process file logs, gateway business logs, backend management logs, and ASP.NET log level configuration.

Configuration ItemDescriptionDefault Value
LoggerOptions.LogLevelTotal log level of process files, optional Trace,Debug,Info, Warning, Error, CriticalInfo
LoggerOptions.ConsoleLogLevelconsole log level; when left empty, follows LogLevelInfo
LoggerOptions.LogPathfile log directoryLogs/XTrace
LoggerOptions.LogFileMaxMegabytesMaximum size of a single log file, 0 means no limit5
LoggerOptions.LogFileBackupsNumber of log files backed up, 0 means no limit10
LoggerOptions.LogFileFormatLog file name format, {0} is date, {1} is log level{0:yyyy_MM_dd}.log

GatewayLogOptions Used to control gate business log retention policies such as acquisition, rules, forwarding, and RPC:

Configuration ItemsDescriptionDefault value
RpcSuccessLogWhether to save RPC success logstrue
RpcLogDaysAgoRPC Log Retention Days30
ChannelLogDaysAgoChannel Log Retention Days30
DeviceLogDaysAgoNumber of days device logs are retained30
RuleEngineLogDaysAgoRule Engine Log Retention Days30
DataForwardLogDaysAgoData Forwarding Runlog Retention Days30
RpcLogMaxRowCountmaximum number of rows in RPC logs, 0 means unlimited;2000000
ChannelLogMaxRowCountmaximum number of channel log rows; 0 means no limit2000000
DeviceLogMaxRowCountmaximum number of line in device logs, 0 means no limit2000000
RuleEngineLogMaxRowCountMaximum number of rule-engine log rows; must be positive and trims oldest rows beyond the limit500000
DataForwardLogMaxRowCountMaximum number of rows in the data forwarding log; 0 means no limit2000000

AdminLogOptions for controlling backend management, operations, SQL, and audit log retention policies:

Configuration ItemsDescriptionDefault Values
OperateLogDaysAgoOperation Log Retention Days30
BackendLogDaysAgoBackend Log Retention Days30
SqlLogDaysAgoSQL Log Retention Days30
AuditLogDaysAgoAudit log retention days30
BackendLogMaxRowCountmaximum backend log row count, 0 indicates no limit2000000
OperateLogMaxRowCountmaximum number of operation log rows, 0 means no limit2000000
SqlLogMaxRowCountMaximum SQL log rows, 0 means no limit2000000
AuditLogMaxRowCountmaximum number of audit log rows, 0 means no limit2000000

The Logging node controls ASP.NET, console, and Windows Event Log levels. By default, Default, Microsoft, and Microsoft.Hosting.Lifetime are set to Warning. Temporarily lower the level when diagnosing framework-level issues, then restore it to avoid excessive logging.

JWTOptions

Configuration ItemsDescriptionDefault Values
IssuerToken issuerThingsGatewayRuntime
ExpiredTimeToken expiration time, measured in minutes21600
AlgorithmSignature AlgorithmHS256
TypeToken TypeJWT
SecretJWT key, supports reading from environment variables${THINGS_GATEWAY_JWT_SECRET:ThingsGatewayRuntime@DefaultSecret#2024}

Production environments must replace the default Secret. Enter a strong key directly, or use $ENVIRONMENT_VARIABLE_NAME or ${ENVIRONMENT_VARIABLE_NAME} to read it from an environment variable. When using an environment variable, confirm that it is set before starting GatewayRuntime. Do not keep using the sample key in production, because different deployments would share the same signing key and weaken token security.

ChannelThread

Configuration ItemDescriptionDefault Value
CheckIntervalInterval between channel and device status checks, unit: milliseconds1800000

Channel, device, and variable limits are no longer read from ChannelThread: the free tier is fixed at 50 channels, 50 devices, and 1000 variables. Once exceeded, the signed limits in the local offline license determine the available capacity. Hardware resources can still impose lower practical limits.

OAuth2Options

Configuration ItemsDescriptionDefault Values
DefaultRoleIdOAuth2 The role ID assigned when automatically creating a local user. When the value is greater than 0, the role0
DefaultRoleCodeOAuth2 is used first, and the role code assigned when the local user is automatically created. DefaultRoleId is not set, the system searches for available roles by role codeadmin
AutoCreateModeOAuth2 How to handle local users when logging in for the first time, values are shown in the table below:Enabled
FrontendCallbackUrlBrowser completes OAuth2 After logging in, the address that returns the web login process/oauth2-callback
CallbackBaseUrlthe base address for callbacks provided by the server to third-party platforms. When deployed behind a reverse proxy, public domain name, or HTTPS gateway, the external address the user actually accesses should be provided, such as https://gateway.example.comhttps://demo.runtime.thingsgateway.cn
Providersthird-party OAuth2 provider configuration, with the key name provider identifier, for example, githubExample configuration containing GitHub

AutoCreateMode available values as follows.

ValueExplanation
Disableddoes not automatically create local users. Only users who have already bound an OAuth2 account can log in
EnabledLocal users are automatically created and enabled on the first OAuth2 login
DisabledPendingReviewAutomatically creates a local user on the first OAuth2 login, but the user is disabled and requires administrator approval to enable
LinkOnlyOnly logged-in users are allowed to bind external accounts; external accounts are not allowed to directly create or log in to local users.

Common configurations for each Providers node are as follows.

Configuration ItemDescription
EnabledWhether to enable this login provider
ClientIdclient ID assigned by the third-party platform. You can enter it directly or read the client key assigned by the
ClientSecretthird-party platform from environment variables. It is recommended to use environment variables for saving production environments and avoid writing to shared configuration files.
AuthorizationUrlThird-party platform authorization address; users will be redirected to this address when clicking external login
TokenUrlUse authorization code to obtain the address for the access token
UserInfoUrlAddress for obtaining third-party user information
ScopesAuthorized scopes, multiple scopes separated by spaces. The GitHub example is read:user user:email
CallbackPathGatewayRuntime. The path to receive third-party callbacks, with the default /api/auth/oauth2/callback. The callback address registered on third-party platforms should be CallbackBaseUrl + CallbackPath
UserNameFieldThe field name that reads the username from third-party user information. GitHub is login
UserIdFieldThe field name reads the user's unique ID from third-party user information. GitHub displays the id
DisplayNamelogin button or login method
StarCheckReposStar checklist from the GitHub repository, formatted as owner/repo. It only checks whether the user has Starred, and does not perform Star operations on behalf of the user.
RequirePkcewhether PKCE is enabled. When third-party platforms support PKCE, it is recommended to enable
AllowInsecureHttpClientto bypass HTTPS certificate verification. It is only recommended to enable it during intranet test certificates or temporary joint debugging; production environments should remain disabled.

t he GitHub provider in the example configuration is used to demonstrate the external login process. Production environments should create their own applications on third-party platforms and prioritize providing ClientId and ClientSecret via environment variables. Do not write demo keys or field keys into shareable configuration packages. When enabling external login, the full callback address should be registered in the third-party platform console, and the GatewayRuntime external access address, HTTPS certificate, client ID, client key, and authorization scope all match.

IdGeneratorOptions

The ID generator uses the snowflake algorithm. Common fields are as follows:

Configuration ItemDescription
MethodSnowflake Algorithm Type.1 is a drift algorithm, suitable for long-term operation and high concurrency; 2 is the traditional algorithm
BaseTimeID time benchmark, using UTC time and cannot be later than host time. Once the system has generated business data, it is not recommended to arbitrarily modify the machine number of the
WorkerIdnode. When running multiple nodes, master-standby nodes, or multiple instances simultaneously, each instance must use a different machine number
WorkerIdBitLengthmachine number occupying bits. The larger the bit, the more nodes can be allocated, but it will crowd out the serial number capacity of a single node.
SeqBitLengthThe number of bits occupied by the serial number within the same slic at the same time. The larger the number of bits, the stronger the ability for a single node to instantly generate IDs.
MaxSeqNumberthe largest serial number, 0 indicates SeqBitLength Automatically uses the maximum
MinSeqNumberthe smallest serial number. It is recommended to keep the default 5, 0-4 as internal reserved range
TopOverCostCountthe maximum drift allowed by the algorithm. For high-concurrency writes, the size can be appropriately increased; for general deployments, keep the default
DataCenterIdData Center ID, used when planning IDs across data centers
DataCenterIdBitLengthThe number of bits occupied by the DataCenter ID. When data center distinctions are not used, maintain 0
TimestampTypetimestamp unit,0 milliseconds, 1 seconds,
SleepTimedrift algorithms use the sleep time as waiting time progresses; ordinary deployments can keep the default

WorkerIdBitLength + SeqBitLength cannot exceed 22. For multi-node deployments, assign each node a WorkerId before starting the services. Do not allow two nodes writing to the same data set to use the same WorkerId.

SeedDataOptions

Configuration ItemsDescriptionDefault Values
ForceUpdateWhether to enable the main switch for forced data initializationtrue
ForceUpdateUsersWhether to force refresh built-in users. This independent control prevents mistaken resets of user login informationfalse
ForceUpdateRoleswhether built-in roles are forced to refresh. When not configured separately, follow ForceUpdatetrue
ForceUpdateMenusWhether to force a menu refresh. When not configured separately, follow ForceUpdatetrue
ForceUpdateMenuLocalesWhether to force a refresh menu localization. When not configured separately, follow ForceUpdatetrue
ForceUpdateButtonsWhether to forcibly refresh button permissions. If not configured separately, follow ForceUpdatetrue

After the production system has defined user, role, menu, or button permissions, the database should be backed up before modifying the forced refresh option. When restoring the system's built-in menu or button, only the corresponding item can be enabled to avoid affecting on-site users and role configurations.