notice.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "bytes"
  22. "encoding/json"
  23. "fmt"
  24. "io"
  25. "os"
  26. "sort"
  27. "strings"
  28. "sync"
  29. "sync/atomic"
  30. "time"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/stacktrace"
  37. )
  38. type noticeLogger struct {
  39. emitDiagnostics int32
  40. emitNetworkParameters int32
  41. mutex sync.Mutex
  42. writer io.Writer
  43. homepageFilename string
  44. homepageFile *os.File
  45. rotatingFilename string
  46. rotatingOlderFilename string
  47. rotatingFile *os.File
  48. rotatingFileSize int64
  49. rotatingCurrentFileSize int64
  50. rotatingSyncFrequency int
  51. rotatingCurrentNoticeCount int
  52. }
  53. var singletonNoticeLogger = noticeLogger{
  54. writer: os.Stderr,
  55. }
  56. // SetEmitDiagnosticNotices toggles whether diagnostic notices are emitted;
  57. // and whether to include circumvention network parameters in diagnostics.
  58. //
  59. // Diagnostic notices contain potentially sensitive user information; and
  60. // sensitive circumvention network parameters, when enabled. Only enable this
  61. // in environments where notices are handled securely (for example, don't
  62. // include these notices in log files which users could post to public
  63. // forums).
  64. func SetEmitDiagnosticNotices(
  65. emitDiagnostics bool, emitNetworkParameters bool) {
  66. if emitDiagnostics {
  67. atomic.StoreInt32(&singletonNoticeLogger.emitDiagnostics, 1)
  68. } else {
  69. atomic.StoreInt32(&singletonNoticeLogger.emitDiagnostics, 0)
  70. }
  71. if emitNetworkParameters {
  72. atomic.StoreInt32(&singletonNoticeLogger.emitNetworkParameters, 1)
  73. } else {
  74. atomic.StoreInt32(&singletonNoticeLogger.emitNetworkParameters, 0)
  75. }
  76. }
  77. // GetEmitDiagnosticNotices returns the current state
  78. // of emitting diagnostic notices.
  79. func GetEmitDiagnosticNotices() bool {
  80. return atomic.LoadInt32(&singletonNoticeLogger.emitDiagnostics) == 1
  81. }
  82. // GetEmitNetworkParameters returns the current state
  83. // of emitting network parameters.
  84. func GetEmitNetworkParameters() bool {
  85. return atomic.LoadInt32(&singletonNoticeLogger.emitNetworkParameters) == 1
  86. }
  87. // SetNoticeWriter sets a target writer to receive notices. By default,
  88. // notices are written to stderr. Notices are newline delimited.
  89. //
  90. // writer specifies an alternate io.Writer where notices are to be written.
  91. //
  92. // Notices are encoded in JSON. Here's an example:
  93. //
  94. // {"data":{"message":"shutdown operate tunnel"},"noticeType":"Info","timestamp":"2006-01-02T15:04:05.999999999Z07:00"}
  95. //
  96. // All notices have the following fields:
  97. // - "noticeType": the type of notice, which indicates the meaning of the notice along with what's in the data payload.
  98. // - "data": additional structured data payload. For example, the "ListeningSocksProxyPort" notice type has a "port" integer
  99. // data in its payload.
  100. // - "timestamp": UTC timezone, RFC3339Milli format timestamp for notice event
  101. //
  102. // See the Notice* functions for details on each notice meaning and payload.
  103. //
  104. func SetNoticeWriter(writer io.Writer) {
  105. singletonNoticeLogger.mutex.Lock()
  106. defer singletonNoticeLogger.mutex.Unlock()
  107. singletonNoticeLogger.writer = writer
  108. }
  109. // setNoticeFiles configures files for notice writing.
  110. //
  111. // - When homepageFilename is not "", homepages are written to the specified file
  112. // and omitted from the writer. The file may be read after the Tunnels notice
  113. // with count of 1. The file should be opened read-only for reading.
  114. //
  115. // - When rotatingFilename is not "", all notices are are written to the specified
  116. // file. Diagnostic notices are omitted from the writer. The file is rotated
  117. // when its size exceeds rotatingFileSize. One rotated older file,
  118. // <rotatingFilename>.1, is retained. The files may be read at any time; and
  119. // should be opened read-only for reading. rotatingSyncFrequency specifies how
  120. // many notices are written before syncing the file.
  121. // If either rotatingFileSize or rotatingSyncFrequency are <= 0, default values
  122. // are used.
  123. //
  124. // - If an error occurs when writing to a file, an InternalError notice is emitted to
  125. // the writer.
  126. //
  127. // setNoticeFiles closes open homepage or rotating files before applying the new
  128. // configuration.
  129. //
  130. func setNoticeFiles(
  131. homepageFilename string,
  132. rotatingFilename string,
  133. rotatingFileSize int,
  134. rotatingSyncFrequency int) error {
  135. singletonNoticeLogger.mutex.Lock()
  136. defer singletonNoticeLogger.mutex.Unlock()
  137. if homepageFilename != "" {
  138. var err error
  139. if singletonNoticeLogger.homepageFile != nil {
  140. singletonNoticeLogger.homepageFile.Close()
  141. }
  142. singletonNoticeLogger.homepageFile, err = os.OpenFile(
  143. homepageFilename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
  144. if err != nil {
  145. return errors.Trace(err)
  146. }
  147. singletonNoticeLogger.homepageFilename = homepageFilename
  148. }
  149. if rotatingFilename != "" {
  150. var err error
  151. if singletonNoticeLogger.rotatingFile != nil {
  152. singletonNoticeLogger.rotatingFile.Close()
  153. }
  154. singletonNoticeLogger.rotatingFile, err = os.OpenFile(
  155. rotatingFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  156. if err != nil {
  157. return errors.Trace(err)
  158. }
  159. fileInfo, err := singletonNoticeLogger.rotatingFile.Stat()
  160. if err != nil {
  161. return errors.Trace(err)
  162. }
  163. if rotatingFileSize <= 0 {
  164. rotatingFileSize = 1 << 20
  165. }
  166. if rotatingSyncFrequency <= 0 {
  167. rotatingSyncFrequency = 100
  168. }
  169. singletonNoticeLogger.rotatingFilename = rotatingFilename
  170. singletonNoticeLogger.rotatingOlderFilename = rotatingFilename + ".1"
  171. singletonNoticeLogger.rotatingFileSize = int64(rotatingFileSize)
  172. singletonNoticeLogger.rotatingCurrentFileSize = fileInfo.Size()
  173. singletonNoticeLogger.rotatingSyncFrequency = rotatingSyncFrequency
  174. singletonNoticeLogger.rotatingCurrentNoticeCount = 0
  175. }
  176. return nil
  177. }
  178. const (
  179. noticeIsDiagnostic = 1
  180. noticeIsHomepage = 2
  181. noticeClearHomepages = 4
  182. noticeSyncHomepages = 8
  183. noticeSkipRedaction = 16
  184. )
  185. // outputNotice encodes a notice in JSON and writes it to the output writer.
  186. func (nl *noticeLogger) outputNotice(noticeType string, noticeFlags uint32, args ...interface{}) {
  187. if (noticeFlags&noticeIsDiagnostic != 0) && !GetEmitDiagnosticNotices() {
  188. return
  189. }
  190. obj := make(map[string]interface{})
  191. noticeData := make(map[string]interface{})
  192. obj["noticeType"] = noticeType
  193. obj["data"] = noticeData
  194. obj["timestamp"] = time.Now().UTC().Format(common.RFC3339Milli)
  195. for i := 0; i < len(args)-1; i += 2 {
  196. name, ok := args[i].(string)
  197. value := args[i+1]
  198. if ok {
  199. noticeData[name] = value
  200. }
  201. }
  202. encodedJson, err := json.Marshal(obj)
  203. var output []byte
  204. if err == nil {
  205. output = append(encodedJson, byte('\n'))
  206. } else {
  207. // Try to emit a properly formatted notice that the outer client can report.
  208. // One scenario where this is useful is if the preceding Marshal fails due to
  209. // bad data in the args. This has happened for a json.RawMessage field.
  210. output = makeNoticeInternalError(
  211. fmt.Sprintf("marshal notice failed: %s", errors.Trace(err)))
  212. }
  213. // Skip redaction when we need to display browsing activity network addresses
  214. // to users; for example, in the case of the Untunneled notice. Never log
  215. // skipRedaction notices to diagnostics files (outputNoticeToRotatingFile,
  216. // below). The notice writer may still be invoked for a skipRedaction notice;
  217. // the writer must keep all known skipRedaction notices out of any upstream
  218. // diagnostics logs.
  219. skipRedaction := (noticeFlags&noticeSkipRedaction != 0)
  220. if !skipRedaction {
  221. // Ensure direct server IPs are not exposed in notices. The "net" package,
  222. // and possibly other 3rd party packages, will include destination addresses
  223. // in I/O error messages.
  224. output = common.RedactIPAddresses(output)
  225. }
  226. // Don't call RedactFilePaths here, as the file path redaction can
  227. // potentially match many non-path strings. Instead, RedactFilePaths should
  228. // be applied in specific cases.
  229. nl.mutex.Lock()
  230. defer nl.mutex.Unlock()
  231. skipWriter := false
  232. if nl.homepageFile != nil &&
  233. (noticeFlags&noticeIsHomepage != 0) {
  234. skipWriter = true
  235. err := nl.outputNoticeToHomepageFile(noticeFlags, output)
  236. if err != nil {
  237. output := makeNoticeInternalError(
  238. fmt.Sprintf("write homepage file failed: %s", err))
  239. nl.writer.Write(output)
  240. }
  241. }
  242. if nl.rotatingFile != nil {
  243. if !skipWriter {
  244. skipWriter = (noticeFlags&noticeIsDiagnostic != 0)
  245. }
  246. if !skipRedaction {
  247. err := nl.outputNoticeToRotatingFile(output)
  248. if err != nil {
  249. output := makeNoticeInternalError(
  250. fmt.Sprintf("write rotating file failed: %s", err))
  251. nl.writer.Write(output)
  252. }
  253. }
  254. }
  255. if !skipWriter {
  256. _, _ = nl.writer.Write(output)
  257. }
  258. }
  259. // NoticeInteralError is an error formatting or writing notices.
  260. // A NoticeInteralError handler must not call a Notice function.
  261. func makeNoticeInternalError(errorMessage string) []byte {
  262. // Format an Alert Notice (_without_ using json.Marshal, since that can fail)
  263. alertNoticeFormat := "{\"noticeType\":\"InternalError\",\"timestamp\":\"%s\",\"data\":{\"message\":\"%s\"}}\n"
  264. return []byte(fmt.Sprintf(alertNoticeFormat, time.Now().UTC().Format(common.RFC3339Milli), errorMessage))
  265. }
  266. func (nl *noticeLogger) outputNoticeToHomepageFile(noticeFlags uint32, output []byte) error {
  267. if (noticeFlags & noticeClearHomepages) != 0 {
  268. err := nl.homepageFile.Truncate(0)
  269. if err != nil {
  270. return errors.Trace(err)
  271. }
  272. _, err = nl.homepageFile.Seek(0, 0)
  273. if err != nil {
  274. return errors.Trace(err)
  275. }
  276. }
  277. _, err := nl.homepageFile.Write(output)
  278. if err != nil {
  279. return errors.Trace(err)
  280. }
  281. if (noticeFlags & noticeSyncHomepages) != 0 {
  282. err = nl.homepageFile.Sync()
  283. if err != nil {
  284. return errors.Trace(err)
  285. }
  286. }
  287. return nil
  288. }
  289. func (nl *noticeLogger) outputNoticeToRotatingFile(output []byte) error {
  290. nl.rotatingCurrentFileSize += int64(len(output) + 1)
  291. if nl.rotatingCurrentFileSize >= nl.rotatingFileSize {
  292. // Note: all errors are fatal in order to preserve the
  293. // rotatingFileSize limit; e.g., no attempt is made to
  294. // continue writing to the file if it can't be rotated.
  295. err := nl.rotatingFile.Sync()
  296. if err != nil {
  297. return errors.Trace(err)
  298. }
  299. err = nl.rotatingFile.Close()
  300. if err != nil {
  301. return errors.Trace(err)
  302. }
  303. err = os.Rename(nl.rotatingFilename, nl.rotatingOlderFilename)
  304. if err != nil {
  305. return errors.Trace(err)
  306. }
  307. nl.rotatingFile, err = os.OpenFile(
  308. nl.rotatingFilename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
  309. if err != nil {
  310. return errors.Trace(err)
  311. }
  312. nl.rotatingCurrentFileSize = 0
  313. }
  314. _, err := nl.rotatingFile.Write(output)
  315. if err != nil {
  316. return errors.Trace(err)
  317. }
  318. nl.rotatingCurrentNoticeCount += 1
  319. if nl.rotatingCurrentNoticeCount >= nl.rotatingSyncFrequency {
  320. nl.rotatingCurrentNoticeCount = 0
  321. err = nl.rotatingFile.Sync()
  322. if err != nil {
  323. return errors.Trace(err)
  324. }
  325. }
  326. return nil
  327. }
  328. // NoticeInfo is an informational message
  329. func NoticeInfo(format string, args ...interface{}) {
  330. singletonNoticeLogger.outputNotice(
  331. "Info", noticeIsDiagnostic,
  332. "message", fmt.Sprintf(format, args...))
  333. }
  334. // NoticeWarning is a warning message; typically a recoverable error condition
  335. func NoticeWarning(format string, args ...interface{}) {
  336. singletonNoticeLogger.outputNotice(
  337. "Warning", noticeIsDiagnostic,
  338. "message", fmt.Sprintf(format, args...))
  339. }
  340. // NoticeError is an error message; typically an unrecoverable error condition
  341. func NoticeError(format string, args ...interface{}) {
  342. singletonNoticeLogger.outputNotice(
  343. "Error", noticeIsDiagnostic,
  344. "message", fmt.Sprintf(format, args...))
  345. }
  346. // NoticeUserLog is a log message from the outer client user of tunnel-core
  347. func NoticeUserLog(message string) {
  348. singletonNoticeLogger.outputNotice(
  349. "UserLog", noticeIsDiagnostic,
  350. "message", message)
  351. }
  352. // NoticeCandidateServers is how many possible servers are available for the selected region and protocols
  353. func NoticeCandidateServers(
  354. region string,
  355. constraints *protocolSelectionConstraints,
  356. initialCount int,
  357. count int,
  358. duration time.Duration) {
  359. singletonNoticeLogger.outputNotice(
  360. "CandidateServers", noticeIsDiagnostic,
  361. "region", region,
  362. "initialLimitTunnelProtocols", constraints.initialLimitTunnelProtocols,
  363. "initialLimitTunnelProtocolsCandidateCount", constraints.initialLimitTunnelProtocolsCandidateCount,
  364. "limitTunnelProtocols", constraints.limitTunnelProtocols,
  365. "limitTunnelDialPortNumbers", constraints.limitTunnelDialPortNumbers,
  366. "replayCandidateCount", constraints.replayCandidateCount,
  367. "initialCount", initialCount,
  368. "count", count,
  369. "duration", duration.String())
  370. }
  371. // NoticeAvailableEgressRegions is what regions are available for egress from.
  372. // Consecutive reports of the same list of regions are suppressed.
  373. func NoticeAvailableEgressRegions(regions []string) {
  374. sortedRegions := append([]string{}, regions...)
  375. sort.Strings(sortedRegions)
  376. repetitionMessage := strings.Join(sortedRegions, "")
  377. outputRepetitiveNotice(
  378. "AvailableEgressRegions", repetitionMessage, 0,
  379. "AvailableEgressRegions", 0, "regions", sortedRegions)
  380. }
  381. func noticeWithDialParameters(noticeType string, dialParams *DialParameters, postDial bool) {
  382. args := []interface{}{
  383. "diagnosticID", dialParams.ServerEntry.GetDiagnosticID(),
  384. "region", dialParams.ServerEntry.Region,
  385. "protocol", dialParams.TunnelProtocol,
  386. "isReplay", dialParams.IsReplay,
  387. "candidateNumber", dialParams.CandidateNumber,
  388. "establishedTunnelsCount", dialParams.EstablishedTunnelsCount,
  389. "networkType", dialParams.GetNetworkType(),
  390. }
  391. if GetEmitNetworkParameters() {
  392. // Omit appliedTacticsTag as that is emitted in another notice.
  393. if dialParams.BPFProgramName != "" {
  394. args = append(args, "clientBPF", dialParams.BPFProgramName)
  395. }
  396. if dialParams.SelectedSSHClientVersion {
  397. args = append(args, "SSHClientVersion", dialParams.SSHClientVersion)
  398. }
  399. if dialParams.UpstreamProxyType != "" {
  400. args = append(args, "upstreamProxyType", dialParams.UpstreamProxyType)
  401. }
  402. if dialParams.UpstreamProxyCustomHeaderNames != nil {
  403. args = append(args, "upstreamProxyCustomHeaderNames", strings.Join(dialParams.UpstreamProxyCustomHeaderNames, ","))
  404. }
  405. if dialParams.FrontingProviderID != "" {
  406. args = append(args, "frontingProviderID", dialParams.FrontingProviderID)
  407. }
  408. if dialParams.MeekDialAddress != "" {
  409. args = append(args, "meekDialAddress", dialParams.MeekDialAddress)
  410. }
  411. if protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  412. meekResolvedIPAddress := dialParams.MeekResolvedIPAddress.Load().(string)
  413. if meekResolvedIPAddress != "" {
  414. nonredacted := common.EscapeRedactIPAddressString(meekResolvedIPAddress)
  415. args = append(args, "meekResolvedIPAddress", nonredacted)
  416. }
  417. }
  418. if dialParams.MeekSNIServerName != "" {
  419. args = append(args, "meekSNIServerName", dialParams.MeekSNIServerName)
  420. }
  421. if dialParams.MeekHostHeader != "" {
  422. args = append(args, "meekHostHeader", dialParams.MeekHostHeader)
  423. }
  424. // MeekTransformedHostName is meaningful when meek is used, which is when MeekDialAddress != ""
  425. if dialParams.MeekDialAddress != "" {
  426. args = append(args, "meekTransformedHostName", dialParams.MeekTransformedHostName)
  427. }
  428. if dialParams.SelectedUserAgent {
  429. args = append(args, "userAgent", dialParams.UserAgent)
  430. }
  431. if dialParams.SelectedTLSProfile {
  432. args = append(args, "TLSProfile", dialParams.TLSProfile)
  433. args = append(args, "TLSVersion", dialParams.GetTLSVersionForMetrics())
  434. }
  435. // dialParams.ServerEntry.Region is emitted above.
  436. if dialParams.ServerEntry.LocalSource != "" {
  437. args = append(args, "serverEntrySource", dialParams.ServerEntry.LocalSource)
  438. }
  439. localServerEntryTimestamp := common.TruncateTimestampToHour(
  440. dialParams.ServerEntry.LocalTimestamp)
  441. if localServerEntryTimestamp != "" {
  442. args = append(args, "serverEntryTimestamp", localServerEntryTimestamp)
  443. }
  444. if dialParams.DialPortNumber != "" {
  445. args = append(args, "dialPortNumber", dialParams.DialPortNumber)
  446. }
  447. if dialParams.QUICVersion != "" {
  448. args = append(args, "QUICVersion", dialParams.QUICVersion)
  449. }
  450. if dialParams.QUICDialSNIAddress != "" {
  451. args = append(args, "QUICDialSNIAddress", dialParams.QUICDialSNIAddress)
  452. }
  453. if dialParams.QUICDisablePathMTUDiscovery {
  454. args = append(args, "QUICDisableClientPathMTUDiscovery", dialParams.QUICDisablePathMTUDiscovery)
  455. }
  456. if dialParams.DialDuration > 0 {
  457. args = append(args, "dialDuration", dialParams.DialDuration)
  458. }
  459. if dialParams.NetworkLatencyMultiplier != 0.0 {
  460. args = append(args, "networkLatencyMultiplier", dialParams.NetworkLatencyMultiplier)
  461. }
  462. if dialParams.ConjureTransport != "" {
  463. args = append(args, "conjureTransport", dialParams.ConjureTransport)
  464. }
  465. if dialParams.ResolveParameters != nil {
  466. if dialParams.ResolveParameters.PreresolvedIPAddress != "" {
  467. nonredacted := common.EscapeRedactIPAddressString(dialParams.ResolveParameters.PreresolvedIPAddress)
  468. args = append(args, "DNSPreresolved", nonredacted)
  469. } else {
  470. // See dialParams.ResolveParameters comment in getBaseAPIParameters.
  471. if dialParams.ResolveParameters.PreferAlternateDNSServer {
  472. nonredacted := common.EscapeRedactIPAddressString(dialParams.ResolveParameters.AlternateDNSServer)
  473. args = append(args, "DNSPreferred", nonredacted)
  474. }
  475. if dialParams.ResolveParameters.ProtocolTransformName != "" {
  476. args = append(args, "DNSTransform", dialParams.ResolveParameters.ProtocolTransformName)
  477. }
  478. if postDial {
  479. args = append(args, "DNSAttempt", dialParams.ResolveParameters.GetFirstAttemptWithAnswer())
  480. }
  481. }
  482. }
  483. if dialParams.DialConnMetrics != nil {
  484. metrics := dialParams.DialConnMetrics.GetMetrics()
  485. for name, value := range metrics {
  486. args = append(args, name, value)
  487. }
  488. }
  489. if dialParams.DialConnNoticeMetrics != nil {
  490. metrics := dialParams.DialConnNoticeMetrics.GetNoticeMetrics()
  491. for name, value := range metrics {
  492. args = append(args, name, value)
  493. }
  494. }
  495. if dialParams.ObfuscatedSSHConnMetrics != nil {
  496. metrics := dialParams.ObfuscatedSSHConnMetrics.GetMetrics()
  497. for name, value := range metrics {
  498. args = append(args, name, value)
  499. }
  500. }
  501. }
  502. singletonNoticeLogger.outputNotice(
  503. noticeType, noticeIsDiagnostic,
  504. args...)
  505. }
  506. // NoticeConnectingServer reports parameters and details for a single connection attempt
  507. func NoticeConnectingServer(dialParams *DialParameters) {
  508. noticeWithDialParameters("ConnectingServer", dialParams, false)
  509. }
  510. // NoticeConnectedServer reports parameters and details for a single successful connection
  511. func NoticeConnectedServer(dialParams *DialParameters) {
  512. noticeWithDialParameters("ConnectedServer", dialParams, true)
  513. }
  514. // NoticeRequestingTactics reports parameters and details for a tactics request attempt
  515. func NoticeRequestingTactics(dialParams *DialParameters) {
  516. noticeWithDialParameters("RequestingTactics", dialParams, false)
  517. }
  518. // NoticeRequestedTactics reports parameters and details for a successful tactics request
  519. func NoticeRequestedTactics(dialParams *DialParameters) {
  520. noticeWithDialParameters("RequestedTactics", dialParams, true)
  521. }
  522. // NoticeActiveTunnel is a successful connection that is used as an active tunnel for port forwarding
  523. func NoticeActiveTunnel(diagnosticID, protocol string, isTCS bool) {
  524. singletonNoticeLogger.outputNotice(
  525. "ActiveTunnel", noticeIsDiagnostic,
  526. "diagnosticID", diagnosticID,
  527. "protocol", protocol,
  528. "isTCS", isTCS)
  529. }
  530. // NoticeSocksProxyPortInUse is a failure to use the configured LocalSocksProxyPort
  531. func NoticeSocksProxyPortInUse(port int) {
  532. singletonNoticeLogger.outputNotice(
  533. "SocksProxyPortInUse", 0,
  534. "port", port)
  535. }
  536. // NoticeListeningSocksProxyPort is the selected port for the listening local SOCKS proxy
  537. func NoticeListeningSocksProxyPort(port int) {
  538. singletonNoticeLogger.outputNotice(
  539. "ListeningSocksProxyPort", 0,
  540. "port", port)
  541. }
  542. // NoticeHttpProxyPortInUse is a failure to use the configured LocalHttpProxyPort
  543. func NoticeHttpProxyPortInUse(port int) {
  544. singletonNoticeLogger.outputNotice(
  545. "HttpProxyPortInUse", 0,
  546. "port", port)
  547. }
  548. // NoticeListeningHttpProxyPort is the selected port for the listening local HTTP proxy
  549. func NoticeListeningHttpProxyPort(port int) {
  550. singletonNoticeLogger.outputNotice(
  551. "ListeningHttpProxyPort", 0,
  552. "port", port)
  553. }
  554. // NoticeClientUpgradeAvailable is an available client upgrade, as per the handshake. The
  555. // client should download and install an upgrade.
  556. func NoticeClientUpgradeAvailable(version string) {
  557. singletonNoticeLogger.outputNotice(
  558. "ClientUpgradeAvailable", 0,
  559. "version", version)
  560. }
  561. // NoticeClientIsLatestVersion reports that an upgrade check was made and the client
  562. // is already the latest version. availableVersion is the version available for download,
  563. // if known.
  564. func NoticeClientIsLatestVersion(availableVersion string) {
  565. singletonNoticeLogger.outputNotice(
  566. "ClientIsLatestVersion", 0,
  567. "availableVersion", availableVersion)
  568. }
  569. // NoticeHomepages emits a series of NoticeHomepage, the sponsor homepages. The client
  570. // should display the sponsor's homepages.
  571. func NoticeHomepages(urls []string) {
  572. for i, url := range urls {
  573. noticeFlags := uint32(noticeIsHomepage)
  574. if i == 0 {
  575. noticeFlags |= noticeClearHomepages
  576. }
  577. if i == len(urls)-1 {
  578. noticeFlags |= noticeSyncHomepages
  579. }
  580. singletonNoticeLogger.outputNotice(
  581. "Homepage", noticeFlags,
  582. "url", url)
  583. }
  584. }
  585. // NoticeClientRegion is the client's region, as determined by the server and
  586. // reported to the client in the handshake.
  587. func NoticeClientRegion(region string) {
  588. singletonNoticeLogger.outputNotice(
  589. "ClientRegion", 0,
  590. "region", region)
  591. }
  592. // NoticeClientAddress is the client's public network address, the IP address
  593. // and port, as seen by the server and reported to the client in the
  594. // handshake.
  595. //
  596. // Note: "address" should remain private and not included in diagnostics logs.
  597. func NoticeClientAddress(address string) {
  598. singletonNoticeLogger.outputNotice(
  599. "ClientAddress", noticeSkipRedaction,
  600. "address", address)
  601. }
  602. // NoticeTunnels is how many active tunnels are available. The client should use this to
  603. // determine connecting/unexpected disconnect state transitions. When count is 0, the core is
  604. // disconnected; when count > 1, the core is connected.
  605. func NoticeTunnels(count int) {
  606. singletonNoticeLogger.outputNotice(
  607. "Tunnels", 0,
  608. "count", count)
  609. }
  610. // NoticeSessionId is the session ID used across all tunnels established by the controller.
  611. func NoticeSessionId(sessionId string) {
  612. singletonNoticeLogger.outputNotice(
  613. "SessionId", noticeIsDiagnostic,
  614. "sessionId", sessionId)
  615. }
  616. // NoticeSplitTunnelRegions reports that split tunnel is on for the given country codes.
  617. func NoticeSplitTunnelRegions(regions []string) {
  618. singletonNoticeLogger.outputNotice(
  619. "SplitTunnelRegions", 0,
  620. "regions", regions)
  621. }
  622. // NoticeUntunneled indicates than an address has been classified as untunneled and is being
  623. // accessed directly.
  624. //
  625. // Note: "address" should remain private; this notice should only be used for alerting
  626. // users, not for diagnostics logs.
  627. func NoticeUntunneled(address string) {
  628. outputRepetitiveNotice(
  629. "Untunneled", address, 0,
  630. "Untunneled", noticeSkipRedaction, "address", address)
  631. }
  632. // NoticeUpstreamProxyError reports an error when connecting to an upstream proxy. The
  633. // user may have input, for example, an incorrect address or incorrect credentials.
  634. func NoticeUpstreamProxyError(err error) {
  635. message := err.Error()
  636. outputRepetitiveNotice(
  637. "UpstreamProxyError", message, 0,
  638. "UpstreamProxyError", 0,
  639. "message", message)
  640. }
  641. // NoticeClientUpgradeDownloadedBytes reports client upgrade download progress.
  642. func NoticeClientUpgradeDownloadedBytes(bytes int64) {
  643. singletonNoticeLogger.outputNotice(
  644. "ClientUpgradeDownloadedBytes", noticeIsDiagnostic,
  645. "bytes", bytes)
  646. }
  647. // NoticeClientUpgradeDownloaded indicates that a client upgrade download
  648. // is complete and available at the destination specified.
  649. func NoticeClientUpgradeDownloaded(filename string) {
  650. singletonNoticeLogger.outputNotice(
  651. "ClientUpgradeDownloaded", 0,
  652. "filename", filename)
  653. }
  654. // NoticeBytesTransferred reports how many tunneled bytes have been
  655. // transferred since the last NoticeBytesTransferred. This is not a diagnostic
  656. // notice: the user app has requested this notice with EmitBytesTransferred
  657. // for functionality such as traffic display; and this frequent notice is not
  658. // intended to be included with feedback.
  659. func NoticeBytesTransferred(diagnosticID string, sent, received int64) {
  660. singletonNoticeLogger.outputNotice(
  661. "BytesTransferred", 0,
  662. "diagnosticID", diagnosticID,
  663. "sent", sent,
  664. "received", received)
  665. }
  666. // NoticeTotalBytesTransferred reports how many tunneled bytes have been
  667. // transferred in total up to this point. This is a diagnostic notice.
  668. func NoticeTotalBytesTransferred(diagnosticID string, sent, received int64) {
  669. singletonNoticeLogger.outputNotice(
  670. "TotalBytesTransferred", noticeIsDiagnostic,
  671. "diagnosticID", diagnosticID,
  672. "sent", sent,
  673. "received", received)
  674. }
  675. // NoticeLocalProxyError reports a local proxy error message. Repetitive
  676. // errors for a given proxy type are suppressed.
  677. func NoticeLocalProxyError(proxyType string, err error) {
  678. // For repeats, only consider the base error message, which is
  679. // the root error that repeats (the full error often contains
  680. // different specific values, e.g., local port numbers, but
  681. // the same repeating root).
  682. // Assumes error format of errors.Trace.
  683. repetitionMessage := err.Error()
  684. index := strings.LastIndex(repetitionMessage, ": ")
  685. if index != -1 {
  686. repetitionMessage = repetitionMessage[index+2:]
  687. }
  688. outputRepetitiveNotice(
  689. "LocalProxyError-"+proxyType, repetitionMessage, 1,
  690. "LocalProxyError", noticeIsDiagnostic,
  691. "message", err.Error())
  692. }
  693. // NoticeBuildInfo reports build version info.
  694. func NoticeBuildInfo() {
  695. singletonNoticeLogger.outputNotice(
  696. "BuildInfo", noticeIsDiagnostic,
  697. "buildInfo", buildinfo.GetBuildInfo())
  698. }
  699. // NoticeExiting indicates that tunnel-core is exiting imminently.
  700. func NoticeExiting() {
  701. singletonNoticeLogger.outputNotice(
  702. "Exiting", 0)
  703. }
  704. // NoticeRemoteServerListResourceDownloadedBytes reports remote server list download progress.
  705. func NoticeRemoteServerListResourceDownloadedBytes(url string, bytes int64, duration time.Duration) {
  706. if !GetEmitNetworkParameters() {
  707. url = "[redacted]"
  708. }
  709. singletonNoticeLogger.outputNotice(
  710. "RemoteServerListResourceDownloadedBytes", noticeIsDiagnostic,
  711. "url", url,
  712. "bytes", bytes,
  713. "duration", duration.String())
  714. }
  715. // NoticeRemoteServerListResourceDownloaded indicates that a remote server list download
  716. // completed successfully.
  717. func NoticeRemoteServerListResourceDownloaded(url string) {
  718. if !GetEmitNetworkParameters() {
  719. url = "[redacted]"
  720. }
  721. singletonNoticeLogger.outputNotice(
  722. "RemoteServerListResourceDownloaded", noticeIsDiagnostic,
  723. "url", url)
  724. }
  725. // NoticeSLOKSeeded indicates that the SLOK with the specified ID was received from
  726. // the Psiphon server. The "duplicate" flags indicates whether the SLOK was previously known.
  727. func NoticeSLOKSeeded(slokID string, duplicate bool) {
  728. singletonNoticeLogger.outputNotice(
  729. "SLOKSeeded", noticeIsDiagnostic,
  730. "slokID", slokID,
  731. "duplicate", duplicate)
  732. }
  733. // NoticeServerTimestamp reports server side timestamp as seen in the handshake.
  734. func NoticeServerTimestamp(diagnosticID string, timestamp string) {
  735. singletonNoticeLogger.outputNotice(
  736. "ServerTimestamp", 0,
  737. "diagnosticID", diagnosticID,
  738. "timestamp", timestamp)
  739. }
  740. // NoticeActiveAuthorizationIDs reports the authorizations the server has accepted.
  741. // Each ID is a base64-encoded accesscontrol.Authorization.ID value.
  742. func NoticeActiveAuthorizationIDs(diagnosticID string, activeAuthorizationIDs []string) {
  743. // Never emit 'null' instead of empty list
  744. if activeAuthorizationIDs == nil {
  745. activeAuthorizationIDs = []string{}
  746. }
  747. singletonNoticeLogger.outputNotice(
  748. "ActiveAuthorizationIDs", 0,
  749. "diagnosticID", diagnosticID,
  750. "IDs", activeAuthorizationIDs)
  751. }
  752. // NoticeTrafficRateLimits reports the tunnel traffic rate limits in place for
  753. // this client, as reported by the server at the start of the tunnel. Values
  754. // of 0 indicate no limit. Values of -1 indicate that the server did not
  755. // report rate limits.
  756. //
  757. // Limitation: any rate limit changes during the lifetime of the tunnel are
  758. // not reported.
  759. func NoticeTrafficRateLimits(
  760. diagnosticID string, upstreamBytesPerSecond, downstreamBytesPerSecond int64) {
  761. singletonNoticeLogger.outputNotice(
  762. "TrafficRateLimits", 0,
  763. "diagnosticID", diagnosticID,
  764. "upstreamBytesPerSecond", upstreamBytesPerSecond,
  765. "downstreamBytesPerSecond", downstreamBytesPerSecond)
  766. }
  767. func NoticeBindToDevice(deviceInfo string) {
  768. outputRepetitiveNotice(
  769. "BindToDevice", deviceInfo, 0,
  770. "BindToDevice", 0, "deviceInfo", deviceInfo)
  771. }
  772. func NoticeNetworkID(networkID string) {
  773. outputRepetitiveNotice(
  774. "NetworkID", networkID, 0,
  775. "NetworkID", 0, "ID", networkID)
  776. }
  777. func NoticeLivenessTest(diagnosticID string, metrics *livenessTestMetrics, success bool) {
  778. if GetEmitNetworkParameters() {
  779. singletonNoticeLogger.outputNotice(
  780. "LivenessTest", noticeIsDiagnostic,
  781. "diagnosticID", diagnosticID,
  782. "metrics", metrics,
  783. "success", success)
  784. }
  785. }
  786. func NoticePruneServerEntry(serverEntryTag string) {
  787. singletonNoticeLogger.outputNotice(
  788. "PruneServerEntry", noticeIsDiagnostic,
  789. "serverEntryTag", serverEntryTag)
  790. }
  791. // NoticeEstablishTunnelTimeout reports that the configured EstablishTunnelTimeout
  792. // duration was exceeded.
  793. func NoticeEstablishTunnelTimeout(timeout time.Duration) {
  794. singletonNoticeLogger.outputNotice(
  795. "EstablishTunnelTimeout", 0,
  796. "timeout", timeout.String())
  797. }
  798. func NoticeFragmentor(diagnosticID string, message string) {
  799. if GetEmitNetworkParameters() {
  800. singletonNoticeLogger.outputNotice(
  801. "Fragmentor", noticeIsDiagnostic,
  802. "diagnosticID", diagnosticID,
  803. "message", message)
  804. }
  805. }
  806. // NoticeApplicationParameters reports application parameters. Each key/value
  807. // parameter pair is emitted in a distinct notice, and each key/value pair is
  808. // reported at most once per session for a fixed value.
  809. func NoticeApplicationParameters(keyValues parameters.KeyValues) {
  810. for key, value := range keyValues {
  811. repetitionKey := fmt.Sprintf("ApplicationParameterKey-%s", key)
  812. outputRepetitiveNotice(
  813. repetitionKey, string(value), 0,
  814. "ApplicationParameter", 0,
  815. "key", key,
  816. "value", value)
  817. }
  818. }
  819. // NoticeServerAlert reports server alerts. Each distinct server alert is
  820. // reported at most once per session.
  821. func NoticeServerAlert(alert protocol.AlertRequest) {
  822. // Never emit 'null' instead of empty list
  823. actionURLs := alert.ActionURLs
  824. if actionURLs == nil {
  825. actionURLs = []string{}
  826. }
  827. // This key ensures that each distinct server alert will appear, not repeat,
  828. // and not interfere with other alerts appearing.
  829. repetitionKey := fmt.Sprintf("ServerAlert-%+v", alert)
  830. outputRepetitiveNotice(
  831. repetitionKey, "", 0,
  832. "ServerAlert", 0,
  833. "reason", alert.Reason,
  834. "subject", alert.Subject,
  835. "actionURLs", actionURLs)
  836. }
  837. // NoticeBursts reports tunnel data transfer burst metrics.
  838. func NoticeBursts(diagnosticID string, burstMetrics common.LogFields) {
  839. if GetEmitNetworkParameters() {
  840. singletonNoticeLogger.outputNotice(
  841. "Bursts", noticeIsDiagnostic,
  842. append([]interface{}{"diagnosticID", diagnosticID}, listCommonFields(burstMetrics)...)...)
  843. }
  844. }
  845. // NoticeHoldOffTunnel reports tunnel hold-offs.
  846. func NoticeHoldOffTunnel(diagnosticID string, duration time.Duration) {
  847. if GetEmitNetworkParameters() {
  848. singletonNoticeLogger.outputNotice(
  849. "HoldOffTunnel", noticeIsDiagnostic,
  850. "diagnosticID", diagnosticID,
  851. "duration", duration.String())
  852. }
  853. }
  854. // NoticeSkipServerEntry reports a reason for skipping a server entry when
  855. // preparing dial parameters. To avoid log noise, the server entry
  856. // diagnosticID is not emitted and each reason is reported at most once per
  857. // session.
  858. func NoticeSkipServerEntry(format string, args ...interface{}) {
  859. reason := fmt.Sprintf(format, args...)
  860. repetitionKey := fmt.Sprintf("SkipServerEntryReason-%+v", reason)
  861. outputRepetitiveNotice(
  862. repetitionKey, "", 0,
  863. "SkipServerEntry", 0, "reason", reason)
  864. }
  865. type repetitiveNoticeState struct {
  866. message string
  867. repeats int
  868. }
  869. var repetitiveNoticeMutex sync.Mutex
  870. var repetitiveNoticeStates = make(map[string]*repetitiveNoticeState)
  871. // outputRepetitiveNotice conditionally outputs a notice. Used for noticies which
  872. // often repeat in noisy bursts. For a repeat limit of N, the notice is emitted
  873. // with a "repeats" count on consecutive repeats up to the limit and then suppressed
  874. // until the repetitionMessage differs.
  875. func outputRepetitiveNotice(
  876. repetitionKey, repetitionMessage string, repeatLimit int,
  877. noticeType string, noticeFlags uint32, args ...interface{}) {
  878. repetitiveNoticeMutex.Lock()
  879. defer repetitiveNoticeMutex.Unlock()
  880. state, keyFound := repetitiveNoticeStates[repetitionKey]
  881. if !keyFound {
  882. state = &repetitiveNoticeState{message: repetitionMessage}
  883. repetitiveNoticeStates[repetitionKey] = state
  884. }
  885. emit := true
  886. if keyFound {
  887. if repetitionMessage != state.message {
  888. state.message = repetitionMessage
  889. state.repeats = 0
  890. } else {
  891. state.repeats += 1
  892. if state.repeats > repeatLimit {
  893. emit = false
  894. }
  895. }
  896. }
  897. if emit {
  898. if state.repeats > 0 {
  899. args = append(args, "repeats", state.repeats)
  900. }
  901. singletonNoticeLogger.outputNotice(
  902. noticeType, noticeFlags,
  903. args...)
  904. }
  905. }
  906. // ResetRepetitiveNotices resets the repetitive notice state, so
  907. // the next instance of any notice will not be supressed.
  908. func ResetRepetitiveNotices() {
  909. repetitiveNoticeMutex.Lock()
  910. defer repetitiveNoticeMutex.Unlock()
  911. repetitiveNoticeStates = make(map[string]*repetitiveNoticeState)
  912. }
  913. type noticeObject struct {
  914. NoticeType string `json:"noticeType"`
  915. Data json.RawMessage `json:"data"`
  916. Timestamp string `json:"timestamp"`
  917. }
  918. // GetNotice receives a JSON encoded object and attempts to parse it as a Notice.
  919. // The type is returned as a string and the payload as a generic map.
  920. func GetNotice(notice []byte) (
  921. noticeType string, payload map[string]interface{}, err error) {
  922. var object noticeObject
  923. err = json.Unmarshal(notice, &object)
  924. if err != nil {
  925. return "", nil, errors.Trace(err)
  926. }
  927. var data interface{}
  928. err = json.Unmarshal(object.Data, &data)
  929. if err != nil {
  930. return "", nil, errors.Trace(err)
  931. }
  932. dataValue, ok := data.(map[string]interface{})
  933. if !ok {
  934. return "", nil, errors.TraceNew("invalid data value")
  935. }
  936. return object.NoticeType, dataValue, nil
  937. }
  938. // NoticeReceiver consumes a notice input stream and invokes a callback function
  939. // for each discrete JSON notice object byte sequence.
  940. type NoticeReceiver struct {
  941. mutex sync.Mutex
  942. buffer []byte
  943. callback func([]byte)
  944. }
  945. // NewNoticeReceiver initializes a new NoticeReceiver
  946. func NewNoticeReceiver(callback func([]byte)) *NoticeReceiver {
  947. return &NoticeReceiver{callback: callback}
  948. }
  949. // Write implements io.Writer.
  950. func (receiver *NoticeReceiver) Write(p []byte) (n int, err error) {
  951. receiver.mutex.Lock()
  952. defer receiver.mutex.Unlock()
  953. receiver.buffer = append(receiver.buffer, p...)
  954. index := bytes.Index(receiver.buffer, []byte("\n"))
  955. if index == -1 {
  956. return len(p), nil
  957. }
  958. notice := receiver.buffer[:index]
  959. receiver.callback(notice)
  960. if index == len(receiver.buffer)-1 {
  961. receiver.buffer = receiver.buffer[0:0]
  962. } else {
  963. receiver.buffer = receiver.buffer[index+1:]
  964. }
  965. return len(p), nil
  966. }
  967. // NewNoticeConsoleRewriter consumes JSON-format notice input and parses each
  968. // notice and rewrites in a more human-readable format more suitable for
  969. // console output. The data payload field is left as JSON.
  970. func NewNoticeConsoleRewriter(writer io.Writer) *NoticeReceiver {
  971. return NewNoticeReceiver(func(notice []byte) {
  972. var object noticeObject
  973. _ = json.Unmarshal(notice, &object)
  974. fmt.Fprintf(
  975. writer,
  976. "%s %s %s\n",
  977. object.Timestamp,
  978. object.NoticeType,
  979. string(object.Data))
  980. })
  981. }
  982. // NoticeWriter implements io.Writer and emits the contents of Write() calls
  983. // as Notices. This is to transform logger messages, if they can be redirected
  984. // to an io.Writer, to notices.
  985. type NoticeWriter struct {
  986. noticeType string
  987. }
  988. // NewNoticeWriter initializes a new NoticeWriter
  989. func NewNoticeWriter(noticeType string) *NoticeWriter {
  990. return &NoticeWriter{noticeType: noticeType}
  991. }
  992. // Write implements io.Writer.
  993. func (writer *NoticeWriter) Write(p []byte) (n int, err error) {
  994. singletonNoticeLogger.outputNotice(
  995. writer.noticeType, noticeIsDiagnostic,
  996. "message", string(p))
  997. return len(p), nil
  998. }
  999. // NoticeCommonLogger maps the common.Logger interface to the notice facility.
  1000. // This is used to make the notice facility available to other packages that
  1001. // don't import the "psiphon" package.
  1002. func NoticeCommonLogger() common.Logger {
  1003. return &commonLogger{}
  1004. }
  1005. type commonLogger struct {
  1006. }
  1007. func (logger *commonLogger) WithTrace() common.LogTrace {
  1008. return &commonLogTrace{
  1009. trace: stacktrace.GetParentFunctionName(),
  1010. }
  1011. }
  1012. func (logger *commonLogger) WithTraceFields(fields common.LogFields) common.LogTrace {
  1013. return &commonLogTrace{
  1014. trace: stacktrace.GetParentFunctionName(),
  1015. fields: fields,
  1016. }
  1017. }
  1018. func (logger *commonLogger) LogMetric(metric string, fields common.LogFields) {
  1019. singletonNoticeLogger.outputNotice(
  1020. metric, noticeIsDiagnostic,
  1021. listCommonFields(fields)...)
  1022. }
  1023. func listCommonFields(fields common.LogFields) []interface{} {
  1024. fieldList := make([]interface{}, 0)
  1025. for name, value := range fields {
  1026. fieldList = append(fieldList, name, value)
  1027. }
  1028. return fieldList
  1029. }
  1030. type commonLogTrace struct {
  1031. trace string
  1032. fields common.LogFields
  1033. }
  1034. func (log *commonLogTrace) outputNotice(
  1035. noticeType string, args ...interface{}) {
  1036. singletonNoticeLogger.outputNotice(
  1037. noticeType, noticeIsDiagnostic,
  1038. append(
  1039. []interface{}{
  1040. "message", fmt.Sprint(args...),
  1041. "trace", log.trace},
  1042. listCommonFields(log.fields)...)...)
  1043. }
  1044. func (log *commonLogTrace) Debug(args ...interface{}) {
  1045. // Ignored.
  1046. }
  1047. func (log *commonLogTrace) Info(args ...interface{}) {
  1048. log.outputNotice("Info", args...)
  1049. }
  1050. func (log *commonLogTrace) Warning(args ...interface{}) {
  1051. log.outputNotice("Alert", args...)
  1052. }
  1053. func (log *commonLogTrace) Error(args ...interface{}) {
  1054. log.outputNotice("Error", args...)
  1055. }