notice.go 38 KB

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